
/***********************************************
* Patch: cs_Schema_Patch_2.1.00
* File Date: 11/29/2006 10:07:18 AM
***********************************************/
Print 'Creating...cs_Schema_Patch_2.1.00'

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--Update Apple release databases to Johnny... Use the 01 patch as a template this
--one has special prerequisite handling

DECLARE @Major int, @Minor int, @Patch int, @Installed DateTime, @Prereqs int

Set @Major = 2;
Set @Minor = 1;
Set @Patch = 0;

Select @Prereqs = isnull(Count(InstallDate),0)  from cs_SchemaVersion where Major=2 and Minor=0 and Patch<58

Select @Installed = InstallDate  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch=@Patch

If(@Installed is null AND @Prereqs = 57)
	BEGIN
--## Schema Patch ##

--All we are doing is updating the schema revision

--## END Schema Patch ##
Insert into cs_SchemaVersion(Major, Minor, Patch, InstallDate) values (@Major, @Minor, @Patch, GetDate())

Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was applied successfully '

	END
ELSE IF(@Installed is not null)
	BEGIN
Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was already applied on ' + Convert(varchar(50), @Installed)  
	END 
ELSE
	BEGIN
Print 'The patch could not be applied because your current schema is missing previous updates (Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ')' 
	END 

/***********************************************
* Patch: cs_Schema_Patch_2.1.01
* File Date: 11/29/2006 10:07:18 AM
***********************************************/
Print 'Creating...cs_Schema_Patch_2.1.01'

-- Add index date field to post table to support re-indexing posts after a
-- specified period of time

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

DECLARE @Major int, @Minor int, @Patch int, @Installed DateTime, @Prereqs int

Set @Major = 2;
Set @Minor = 1;
Set @Patch = 1;

Select @Prereqs = isnull(Count(InstallDate),0)  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch<@Patch

Select @Installed = InstallDate  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch=@Patch

If(@Installed is null AND @Prereqs = @Patch)
	BEGIN
--## Schema Patch ##
	
exec sp_ExecuteSQL N'ALTER TABLE [dbo].[cs_Posts] ADD [IndexDate] [smalldatetime]' 

--note the following line needs to be in sp_ExecuteSQL because the referenced column does not exist when SQL initally
--evaluates the SQL patch and will cause an error IndexDate does not exist...

--note - due to the potential that this update will take a very long time so we will allow the column to be null
--and account for it in the corrisponding job
--exec sp_ExecuteSQL N'UPDATE [dbo].[cs_Posts] SET [IndexDate] = [PostDate] WHERE IsIndexed = 1'


--## END Schema Patch ##
Insert into cs_SchemaVersion(Major, Minor, Patch, InstallDate) values (@Major, @Minor, @Patch, GetDate())

Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was applied successfully '

	END
ELSE IF(@Installed is not null)
	BEGIN
Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was already applied on ' + Convert(varchar(50), @Installed)  
	END 
ELSE
	BEGIN
Print 'The patch could not be applied because your current schema is missing previous updates (Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ')' 
	END 

/***********************************************
* Patch: cs_Schema_Patch_2.1.02
* File Date: 11/29/2006 10:07:18 AM
***********************************************/
Print 'Creating...cs_Schema_Patch_2.1.02'

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

DECLARE @Major int, @Minor int, @Patch int, @Installed DateTime, @Prereqs int

Set @Major = 2;
Set @Minor = 1;
Set @Patch = 2;

Select @Prereqs = isnull(Count(InstallDate),0)  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch<@Patch

Select @Installed = InstallDate  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch=@Patch

If(@Installed is null AND @Prereqs = @Patch)
	BEGIN
--## Schema Patch ##
	
exec sp_ExecuteSQL N'ALTER TABLE dbo.cs_Sections ADD DefaultLanguage nvarchar(32) NULL' 

--## END Schema Patch ##
Insert into cs_SchemaVersion(Major, Minor, Patch, InstallDate) values (@Major, @Minor, @Patch, GetDate())

Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was applied successfully '

	END
ELSE IF(@Installed is not null)
	BEGIN
Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was already applied on ' + Convert(varchar(50), @Installed)  
	END 
ELSE
	BEGIN
Print 'The patch could not be applied because your current schema is missing previous updates (Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ')' 
	END 

/***********************************************
* Patch: cs_Schema_Patch_2.1.03
* File Date: 11/29/2006 10:07:18 AM
***********************************************/
Print 'Creating...cs_Schema_Patch_2.1.03'

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

DECLARE @Major int, @Minor int, @Patch int, @Installed DateTime, @Prereqs int

Set @Major = 2;
Set @Minor = 1;
Set @Patch = 3;

Select @Prereqs = isnull(Count(InstallDate),0)  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch<@Patch

Select @Installed = InstallDate  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch=@Patch

If(@Installed is null AND @Prereqs = @Patch)
	BEGIN
--## Schema Patch ##
	
CREATE TABLE [dbo].[cs_PageViews](
	[URL] [nvarchar](512) NOT NULL,
	[VisitCount] [int] NOT NULL,
	[DateTimeStamp] [datetime] NOT NULL
) ON [PRIMARY]

--## END Schema Patch ##
Insert into cs_SchemaVersion(Major, Minor, Patch, InstallDate) values (@Major, @Minor, @Patch, GetDate())

Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was applied successfully '

	END
ELSE IF(@Installed is not null)
	BEGIN
Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was already applied on ' + Convert(varchar(50), @Installed)  
	END 
ELSE
	BEGIN
Print 'The patch could not be applied because your current schema is missing previous updates (Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ')' 
	END 

/***********************************************
* Patch: cs_Schema_Patch_2.1.04
* File Date: 11/29/2006 10:07:18 AM
***********************************************/
Print 'Creating...cs_Schema_Patch_2.1.04'

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

DECLARE @Major int, @Minor int, @Patch int, @Installed DateTime, @Prereqs int

Set @Major = 2;
Set @Minor = 1;
Set @Patch = 4;

Select @Prereqs = isnull(Count(InstallDate),0)  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch<@Patch

Select @Installed = InstallDate  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch=@Patch

If(@Installed is null AND @Prereqs = @Patch)
	BEGIN
--## Schema Patch ##
	
exec sp_ExecuteSQL N'ALTER TABLE dbo.cs_statistics_Site ADD ViewCount int NOT NULL DEFAULT 0'
exec sp_ExecuteSQL N'ALTER TABLE dbo.cs_statistics_Site ADD ReplyCount int NOT NULL DEFAULT 0' 

--## END Schema Patch ##
Insert into cs_SchemaVersion(Major, Minor, Patch, InstallDate) values (@Major, @Minor, @Patch, GetDate())

Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was applied successfully '

	END
ELSE IF(@Installed is not null)
	BEGIN
Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was already applied on ' + Convert(varchar(50), @Installed)  
	END 
ELSE
	BEGIN
Print 'The patch could not be applied because your current schema is missing previous updates (Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ')' 
	END 

/***********************************************
* Patch: cs_Schema_Patch_2.1.05
* File Date: 11/29/2006 10:07:18 AM
***********************************************/
Print 'Creating...cs_Schema_Patch_2.1.05'

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

DECLARE @Major int, @Minor int, @Patch int, @Installed DateTime, @Prereqs int

Set @Major = 2;
Set @Minor = 1;
Set @Patch = 5;

Select @Prereqs = isnull(Count(InstallDate),0)  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch<@Patch

Select @Installed = InstallDate  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch=@Patch

If(@Installed is null AND @Prereqs = @Patch)
	BEGIN
--## Schema Patch ##

--This sql patch updates are no longer required, the API has been updated to accept nulls
--The patch takes too long on large databases
	
--update cs_Posts Set UserTime = PostDate where UserTime is null
--ALTER TABLE cs_posts ALTER COLUMN UserTime DateTime NOT NULL 

--## END Schema Patch ##
Insert into cs_SchemaVersion(Major, Minor, Patch, InstallDate) values (@Major, @Minor, @Patch, GetDate())

Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was applied successfully '

	END
ELSE IF(@Installed is not null)
	BEGIN
Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was already applied on ' + Convert(varchar(50), @Installed)  
	END 
ELSE
	BEGIN
Print 'The patch could not be applied because your current schema is missing previous updates (Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ')' 
	END 

/***********************************************
* Patch: cs_Schema_Patch_2.1.06
* File Date: 11/29/2006 10:07:18 AM
***********************************************/
Print 'Creating...cs_Schema_Patch_2.1.06'

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

DECLARE @Major int, @Minor int, @Patch int, @Installed DateTime, @Prereqs int

Set @Major = 2;
Set @Minor = 1;
Set @Patch = 6;

Select @Prereqs = isnull(Count(InstallDate),0)  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch<@Patch

Select @Installed = InstallDate  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch=@Patch

If(@Installed is null AND @Prereqs = @Patch)
	BEGIN
--## Schema Patch ##
	
if not exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[csm_MailingLists]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
begin
	exec sp_ExecuteSQL N'CREATE TABLE [dbo].[csm_MailingLists] (
		[SectionID] [int] NOT NULL ,
		[EmailAddress] [nvarchar] (100) NOT NULL ,
		[IsMailingList] [bit] NOT NULL ,
		[SettingsID] [int] NOT NULL 
	) ON [PRIMARY]'

	exec sp_ExecuteSQL N'ALTER TABLE [dbo].[csm_MailingLists] WITH NOCHECK ADD 
		CONSTRAINT [PK_le_MailingList] PRIMARY KEY  CLUSTERED 
		(
			[SectionID],
			[SettingsID]
		)  ON [PRIMARY]'
end

if not exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[csm_EmailIds]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
begin
	exec sp_ExecuteSQL N'CREATE TABLE [dbo].[csm_EmailIds] (
		[EmailID] [bigint] NOT NULL ,
		[UserID] [int] NOT NULL ,
		[SectionID] [int] NOT NULL 
	) ON [PRIMARY]'

	exec sp_ExecuteSQL N'ALTER TABLE [dbo].[csm_EmailIds] WITH NOCHECK ADD 
		CONSTRAINT [PK_csm_EmailIds] PRIMARY KEY  CLUSTERED 
		(
			[EmailID]
		)  ON [PRIMARY]'
end

--## END Schema Patch ##
Insert into cs_SchemaVersion(Major, Minor, Patch, InstallDate) values (@Major, @Minor, @Patch, GetDate())

Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was applied successfully '

	END
ELSE IF(@Installed is not null)
	BEGIN
Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was already applied on ' + Convert(varchar(50), @Installed)  
	END 
ELSE
	BEGIN
Print 'The patch could not be applied because your current schema is missing previous updates (Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ')' 
	END 

/***********************************************
* Patch: cs_Schema_Patch_2.1.07
* File Date: 11/29/2006 10:07:18 AM
***********************************************/
Print 'Creating...cs_Schema_Patch_2.1.07'

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

DECLARE @Major int, @Minor int, @Patch int, @Installed DateTime, @Prereqs int

Set @Major = 2;
Set @Minor = 1;
Set @Patch = 7;

Select @Prereqs = isnull(Count(InstallDate),0)  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch<@Patch

Select @Installed = InstallDate  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch=@Patch

If(@Installed is null AND @Prereqs = @Patch)
	BEGIN
--## Schema Patch ##

	
if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[FK_cs_RollerBlogPost_cs_RollerBlogFeeds]') and OBJECTPROPERTY(id, N'IsForeignKey') = 1)
exec sp_ExecuteSQL N'ALTER TABLE [dbo].[cs_RollerBlogPost] DROP CONSTRAINT FK_cs_RollerBlogPost_cs_RollerBlogFeeds'


if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[FK_cs_RollerBlogFeeds_cs_RollerBlogUrls]') and OBJECTPROPERTY(id, N'IsForeignKey') = 1)
exec sp_ExecuteSQL N'ALTER TABLE [dbo].[cs_RollerBlogFeeds] DROP CONSTRAINT FK_cs_RollerBlogFeeds_cs_RollerBlogUrls'


if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_RollerBlogFeeds]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
exec sp_ExecuteSQL N'drop table [dbo].[cs_RollerBlogFeeds]'


if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_RollerBlogPost]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
exec sp_ExecuteSQL N'drop table [dbo].[cs_RollerBlogPost]'


if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_RollerBlogUrls]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
exec sp_ExecuteSQL N'drop table [dbo].[cs_RollerBlogUrls]'


exec sp_ExecuteSQL N'CREATE TABLE [dbo].[cs_RollerBlogFeeds] (
	[SectionID] [int] NOT NULL ,
	[SettingsID] [int] NOT NULL ,
	[UrlID] [int] NOT NULL ,
	[Enabled] [bit] NOT NULL ,
	[IntervalMinutes] [int] NOT NULL ,
	[Title] [nvarchar] (256) NULL ,
	[PostFullArticle] [bit] NOT NULL ,
	[ExerptSize] [int] NOT NULL ,
	[SubscribeDate] [datetime] NOT NULL ,
	[LastUpdateDate] [datetime] NOT NULL ,
	[LastModifiedDate] [datetime] NOT NULL ,
	[ETag] [nvarchar] (256) NULL ,
	[State] [int] NOT NULL 
) ON [PRIMARY]'


exec sp_ExecuteSQL N'CREATE TABLE [dbo].[cs_RollerBlogPost] (
	[SectionID] [int] NOT NULL ,
	[UrlId] [int] NOT NULL ,
	[PostID] [int] NOT NULL ,
	[PermaLink] [nvarchar] (512) NOT NULL ,
	[CommentUrl] [nvarchar] (512)  NULL ,
	[CommentCount] [int] NULL ,
	[GuidName] [nvarchar] (512) NULL ,
	[GuidIsPermaLink] [bit] NOT NULL 
) ON [PRIMARY]'

exec sp_ExecuteSQL N'CREATE TABLE [dbo].[cs_RollerBlogUrls] (
	[UrlID] [int] IDENTITY (1, 1) NOT NULL ,
	[Url] [nvarchar] (512) NOT NULL 
) ON [PRIMARY]'

exec sp_ExecuteSQL N'ALTER TABLE [dbo].[cs_RollerBlogFeeds] ADD 
	CONSTRAINT [DF_cs_RollerBlogFeeds_Enabled] DEFAULT (1) FOR [Enabled],
	CONSTRAINT [DF_cs_RollerBlogFeeds_IntervalMinutes] DEFAULT (5) FOR [IntervalMinutes],
	CONSTRAINT [DF_cs_RollerBlogFeeds_PostFullArticle] DEFAULT (0) FOR [PostFullArticle],
	CONSTRAINT [DF_cs_RollerBlogFeeds_ExerptSize] DEFAULT (256) FOR [ExerptSize],
	CONSTRAINT [DF_cs_RollerBlogFeeds_State] DEFAULT (0) FOR [State],
	CONSTRAINT [PK_cs_RollerBlogFeeds] PRIMARY KEY  CLUSTERED 
	(
		[SectionID],
		[UrlID]
	)  ON [PRIMARY]'

exec sp_ExecuteSQL N'ALTER TABLE [dbo].[cs_RollerBlogPost] ADD 
	CONSTRAINT [PK_cs_RollerBlogPost] PRIMARY KEY  CLUSTERED 
	(
		[SectionID],
		[UrlId],
		[PostID]
	)  ON [PRIMARY]'

exec sp_ExecuteSQL N'ALTER TABLE [dbo].[cs_RollerBlogUrls] ADD 
	CONSTRAINT [PK_cs_RollerBlogUrls] PRIMARY KEY  CLUSTERED 
	(
		[UrlID]
	)  ON [PRIMARY]'

exec sp_ExecuteSQL N'ALTER TABLE [dbo].[cs_RollerBlogFeeds] ADD 
	CONSTRAINT [FK_cs_RollerBlogFeeds_cs_RollerBlogUrls] FOREIGN KEY 
	(
		[UrlID]
	) REFERENCES [dbo].[cs_RollerBlogUrls] (
		[UrlID]
	),
	CONSTRAINT [FK_cs_RollerBlogFeeds_cs_Sections] FOREIGN KEY 
	(
		[SettingsID],
		[SectionID]
	) REFERENCES [dbo].[cs_Sections] (
		[SettingsID],
		[SectionID]
	)'

exec sp_ExecuteSQL N'ALTER TABLE [dbo].[cs_RollerBlogPost] ADD 
	CONSTRAINT [FK_cs_RollerBlogPost_cs_RollerBlogFeeds] FOREIGN KEY 
	(
		[SectionID],
		[UrlId]
	) REFERENCES [dbo].[cs_RollerBlogFeeds] (
		[SectionID],
		[UrlID]
	)'



--## END Schema Patch ##
Insert into cs_SchemaVersion(Major, Minor, Patch, InstallDate) values (@Major, @Minor, @Patch, GetDate())

Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was applied successfully '

	END
ELSE IF(@Installed is not null)
	BEGIN
Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was already applied on ' + Convert(varchar(50), @Installed)  
	END 
ELSE
	BEGIN
Print 'The patch could not be applied because your current schema is missing previous updates (Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ')' 
	END 

/***********************************************
* Patch: cs_Schema_Patch_2.1.08
* File Date: 11/29/2006 10:07:18 AM
***********************************************/
Print 'Creating...cs_Schema_Patch_2.1.08'

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

DECLARE @Major int, @Minor int, @Patch int, @Installed DateTime, @Prereqs int

Set @Major = 2;
Set @Minor = 1;
Set @Patch = 8;

Select @Prereqs = isnull(Count(InstallDate),0)  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch<@Patch

Select @Installed = InstallDate  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch=@Patch

If(@Installed is null AND @Prereqs = @Patch)
	BEGIN
--## Schema Patch ##

alter table cs_PostMetadata alter column MetaKey nvarchar(100) not null
alter table cs_PostMetadata alter column MetaType nvarchar(100) not null
alter table cs_PostMetadata alter column MetaValue nvarchar(100) not null

--## END Schema Patch ##
Insert into cs_SchemaVersion(Major, Minor, Patch, InstallDate) values (@Major, @Minor, @Patch, GetDate())

Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was applied successfully '

	END
ELSE IF(@Installed is not null)
	BEGIN
Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was already applied on ' + Convert(varchar(50), @Installed)  
	END 
ELSE
	BEGIN
Print 'The patch could not be applied because your current schema is missing previous updates (Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ')' 
	END 

/***********************************************
* Patch: cs_Schema_Patch_2.1.09
* File Date: 11/29/2006 10:07:18 AM
***********************************************/
Print 'Creating...cs_Schema_Patch_2.1.09'

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

DECLARE @Major int, @Minor int, @Patch int, @Installed DateTime, @Prereqs int

Set @Major = 2;
Set @Minor = 1;
Set @Patch = 9;

Select @Prereqs = isnull(Count(InstallDate),0)  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch<@Patch

Select @Installed = InstallDate  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch=@Patch

If(@Installed is null AND @Prereqs = @Patch)
	BEGIN
--## Schema Patch ##

exec sp_ExecuteSQL N'ALTER TABLE [dbo].[cs_UserAvatar]
Add [Length] [int] NULL,
[ContentType] [nvarchar] (64) NULL,
[Content] [image] NULL,
[DateLastUpdated] [datetime] NOT NULL CONSTRAINT [DF_cs_UserAvatar_DateLastUpdated] DEFAULT (getdate())'

exec sp_ExecuteSQL N'UPDATE [dbo].[cs_UserAvatar] SET Length = i.Length, ContentType = i.ContentType, [Content] = i.[Content], [DateLastUpdated] = i.[DateLastUpdated] 
	FROM [dbo].[cs_UserAvatar] a JOIN [dbo].[cs_Images] i on i.ImageID = a.ImageID'
	
if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[FK_cs_UserAvatar_cs_Images]') and OBJECTPROPERTY(id, N'IsForeignKey') = 1)
exec sp_ExecuteSQL N'ALTER TABLE [dbo].[cs_UserAvatar] DROP CONSTRAINT [FK_cs_UserAvatar_cs_Images]'

exec sp_ExecuteSQL N'ALTER TABLE [dbo].[cs_UserAvatar] DROP COLUMN [ImageID]'

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Images]') and OBJECTPROPERTY(id, N'IsTable') = 1)
exec sp_ExecuteSQL N'DROP TABLE [dbo].[cs_Images]'

--SQL 2000 cant handle altering an image col
--exec sp_ExecuteSQL N'ALTER TABLE [dbo].[cs_UserAvatar]
--ALTER COLUMN [Content] [image] NOT NULL'

--## END Schema Patch ##
Insert into cs_SchemaVersion(Major, Minor, Patch, InstallDate) values (@Major, @Minor, @Patch, GetDate())

Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was applied successfully '

	END
ELSE IF(@Installed is not null)
	BEGIN
Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was already applied on ' + Convert(varchar(50), @Installed)  
	END 
ELSE
	BEGIN
Print 'The patch could not be applied because your current schema is missing previous updates (Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ')' 
	END 

/***********************************************
* Patch: cs_Schema_Patch_2.1.10
* File Date: 11/29/2006 10:07:18 AM
***********************************************/
Print 'Creating...cs_Schema_Patch_2.1.10'

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

DECLARE @Major int, @Minor int, @Patch int, @Installed DateTime, @Prereqs int

Set @Major = 2;
Set @Minor = 1;
Set @Patch = 10;

Select @Prereqs = isnull(Count(InstallDate),0)  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch<@Patch

Select @Installed = InstallDate  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch=@Patch

If(@Installed is null AND @Prereqs = @Patch)
	BEGIN
--## Schema Patch ##
	
exec sp_ExecuteSQL N'ALTER TABLE dbo.cs_RollerBlogFeeds ADD IsBlogAggregated bit NOT NULL DEFAULT 1'
exec sp_ExecuteSQL N'ALTER TABLE dbo.cs_RollerBlogFeeds ADD IsBlogRollAggregated bit NOT NULL DEFAULT 1'
exec sp_ExecuteSQL N'ALTER TABLE dbo.cs_RollerBlogFeeds ADD IsRollerBlogAggregated bit NOT NULL DEFAULT 1'

--## END Schema Patch ##
Insert into cs_SchemaVersion(Major, Minor, Patch, InstallDate) values (@Major, @Minor, @Patch, GetDate())

Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was applied successfully '

	END
ELSE IF(@Installed is not null)
	BEGIN
Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was already applied on ' + Convert(varchar(50), @Installed)  
	END 
ELSE
	BEGIN
Print 'The patch could not be applied because your current schema is missing previous updates (Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ')' 
	END 

/***********************************************
* Patch: cs_Schema_Patch_2.1.11
* File Date: 11/29/2006 10:07:18 AM
***********************************************/
Print 'Creating...cs_Schema_Patch_2.1.11'

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

DECLARE @Major int, @Minor int, @Patch int, @Installed DateTime, @Prereqs int

Set @Major = 2;
Set @Minor = 1;
Set @Patch = 11;

Select @Prereqs = isnull(Count(InstallDate),0)  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch<@Patch

Select @Installed = InstallDate  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch=@Patch

If(@Installed is null AND @Prereqs = @Patch)
	BEGIN
--## Schema Patch ##

exec sp_ExecuteSQL N'ALTER TABLE cs_Posts ADD
	PostMedia int NOT NULL CONSTRAINT DF_cs_Posts_PostMedia DEFAULT 0'

-- Video
exec sp_ExecuteSQL N'UPDATE cs_Posts SET PostMedia = 2, PostType = 1 WHERE PostType = 4'

-- Polls (within forums)
exec sp_ExecuteSQL N'UPDATE cs_Posts SET PostMedia = 8 WHERE PostType = 2 OR (ApplicationPostType = 2 and SectionID in (select SectionID from cs_Sections where ApplicationType = 0))' 

-- Image
exec sp_ExecuteSQL N'UPDATE cs_Posts SET PostMedia = 1, PostType = 1 WHERE PostType = 3'

-- Set PostMedia to Image for all Photo Gallery posts
exec sp_ExecuteSQL N'UPDATE cs_Posts SET PostMedia = 1 WHERE PostMedia=0
		AND (SectionID IN (Select s.SectionID From cs_Sections s Where s.ApplicationType = 2))'

-- Reset all Forum PostTypes to Post (1)
exec sp_ExecuteSQL N'UPDATE cs_Posts SET ApplicationPostType = 1 WHERE ApplicationPostType <> 1
		AND (SectionID IN (Select s.SectionID From cs_Sections s Where s.ApplicationType = 0))'

--## END Schema Patch ##
Insert into cs_SchemaVersion(Major, Minor, Patch, InstallDate) values (@Major, @Minor, @Patch, GetDate())

Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was applied successfully '

	END
ELSE IF(@Installed is not null)
	BEGIN
Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was already applied on ' + Convert(varchar(50), @Installed)  
	END 
ELSE
	BEGIN
Print 'The patch could not be applied because your current schema is missing previous updates (Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ')' 
	END 


/***********************************************
* Patch: cs_Schema_Patch_2.1.12
* File Date: 11/29/2006 10:07:18 AM
***********************************************/
Print 'Creating...cs_Schema_Patch_2.1.12'

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

DECLARE @Major int, @Minor int, @Patch int, @Installed DateTime, @Prereqs int

Set @Major = 2;
Set @Minor = 1;
Set @Patch = 12;

Select @Prereqs = isnull(Count(InstallDate),0)  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch<@Patch

Select @Installed = InstallDate  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch=@Patch

If(@Installed is null AND @Prereqs = @Patch)
	BEGIN
--## Schema Patch ##

update cs_Posts Set PostName = Replace(PostName,'_',' ') where PostName is not null

--## END Schema Patch ##
Insert into cs_SchemaVersion(Major, Minor, Patch, InstallDate) values (@Major, @Minor, @Patch, GetDate())

Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was applied successfully '

	END
ELSE IF(@Installed is not null)
	BEGIN
Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was already applied on ' + Convert(varchar(50), @Installed)  
	END 
ELSE
	BEGIN
Print 'The patch could not be applied because your current schema is missing previous updates (Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ')' 
	END 


/***********************************************
* Patch: cs_Schema_Patch_2.1.13
* File Date: 11/29/2006 10:07:18 AM
***********************************************/
Print 'Creating...cs_Schema_Patch_2.1.13'

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

DECLARE @Major int, @Minor int, @Patch int, @Installed DateTime, @Prereqs int

Set @Major = 2;
Set @Minor = 1;
Set @Patch = 13;

Select @Prereqs = isnull(Count(InstallDate),0)  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch<@Patch

Select @Installed = InstallDate  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch=@Patch

If(@Installed is null AND @Prereqs = @Patch)
	BEGIN
--## Schema Patch ##

exec sp_ExecuteSQL N'CREATE TABLE [dbo].[cs_UserInvitation] (
	[InvitationKey]  uniqueidentifier ROWGUIDCOL  NOT NULL ,
	[UserID] [int] NOT NULL ,
	[Email] [nvarchar] (255) NOT NULL ,
	[DateInvited] [datetime] NOT NULL 
) ON [PRIMARY]'

exec sp_ExecuteSQL N'ALTER TABLE [dbo].[cs_UserInvitation] WITH NOCHECK ADD 
	CONSTRAINT [PK_cs_UserInvitation] PRIMARY KEY  CLUSTERED 
	(
		[InvitationKey]
	)  ON [PRIMARY]'

exec sp_ExecuteSQL N'ALTER TABLE [dbo].[cs_UserInvitation] ADD 
	CONSTRAINT [DF_cs_UserInvitation_InvitationKey] DEFAULT (newid()) FOR [InvitationKey],
	CONSTRAINT [DF_cs_UserInvitation_DateInvited] DEFAULT (getdate()) FOR [DateInvited]'

exec sp_ExecuteSQL N'ALTER TABLE dbo.cs_UserInvitation ADD
	PropertyNames ntext NULL,
	PropertyValues ntext NULL'

--## END Schema Patch ##
Insert into cs_SchemaVersion(Major, Minor, Patch, InstallDate) values (@Major, @Minor, @Patch, GetDate())

Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was applied successfully '

	END
ELSE IF(@Installed is not null)
	BEGIN
Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was already applied on ' + Convert(varchar(50), @Installed)  
	END 
ELSE
	BEGIN
Print 'The patch could not be applied because your current schema is missing previous updates (Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ')' 
	END 


/***********************************************
* Patch: cs_Schema_Patch_2.1.14
* File Date: 11/29/2006 10:07:18 AM
***********************************************/
Print 'Creating...cs_Schema_Patch_2.1.14'

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

DECLARE @Major int, @Minor int, @Patch int, @Installed DateTime, @Prereqs int

Set @Major = 2;
Set @Minor = 1;
Set @Patch = 14;

Select @Prereqs = isnull(Count(InstallDate),0)  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch<@Patch

Select @Installed = InstallDate  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch=@Patch

If(@Installed is null AND @Prereqs = @Patch)
	BEGIN
--## Schema Patch ##

if not exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[csm_Sections_MailingLists_Delete]') and OBJECTPROPERTY(id, N'IsTrigger') = 1)
begin
	exec sp_ExecuteSQL N'CREATE TRIGGER csm_Sections_MailingLists_Delete ON cs_Sections
	FOR DELETE
	AS
	BEGIN
		DELETE FROM csm_MailingLists WHERE SectionID IN (SELECT SectionID FROM DELETED)
		DELETE FROM csm_EmailIds WHERE SectionID IN (SELECT SectionID FROM DELETED)
	END'
end

--## END Schema Patch ##
Insert into cs_SchemaVersion(Major, Minor, Patch, InstallDate) values (@Major, @Minor, @Patch, GetDate())

Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was applied successfully '

	END
ELSE IF(@Installed is not null)
	BEGIN
Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was already applied on ' + Convert(varchar(50), @Installed)  
	END 
ELSE
	BEGIN
Print 'The patch could not be applied because your current schema is missing previous updates (Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ')' 
	END 


/***********************************************
* Patch: cs_Schema_Patch_2.1.15
* File Date: 11/29/2006 10:07:18 AM
***********************************************/
Print 'Creating...cs_Schema_Patch_2.1.15'

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

DECLARE @Major int, @Minor int, @Patch int, @Installed DateTime, @Prereqs int

Set @Major = 2;
Set @Minor = 1;
Set @Patch = 15;

Select @Prereqs = isnull(Count(InstallDate),0)  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch<@Patch

Select @Installed = InstallDate  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch=@Patch

If(@Installed is null AND @Prereqs = @Patch)
	BEGIN
--## Schema Patch ##
/*****************************************  This has been moved to an addon ********************************************
if not exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_RssCtrl]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
begin
	exec sp_ExecuteSQL N'CREATE TABLE [dbo].[cs_RssCtrl] (
	[CtrlID] [int] NOT NULL ,
	[Title] [varchar] (256) NOT NULL ,
	[Name] [varchar] (256) NOT NULL ,
	[ExerptSize] [int] NOT NULL ,
	[PostCount] [int] NULL 
	) ON [PRIMARY]'

	exec sp_ExecuteSQL N'ALTER TABLE [dbo].[cs_RssCtrl] ADD 
	CONSTRAINT [DF_RssCtrl_ExerptSize] DEFAULT (125) FOR [ExerptSize],
	CONSTRAINT [DF_cs_RssCtrl_PostCount] DEFAULT (3) FOR [PostCount]'

	exec sp_ExecuteSQL N'CREATE  UNIQUE  INDEX [IX_cs_RssCtrl] ON [dbo].[cs_RssCtrl]([CtrlID]) ON [PRIMARY]'
end

if not exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_RssCtrlFeeds]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
begin
	exec sp_ExecuteSQL N'CREATE TABLE [dbo].[cs_RssCtrlFeeds] (
	[CtrlID] [int] NOT NULL ,
	[UrlID] [int] NOT NULL ,
	[Enabled] [bit] NOT NULL ,
	[Title] [nvarchar] (256) NOT NULL ,
	[SubscribeDate] [datetime] NOT NULL ,
	[LastUpdateDate] [datetime] NOT NULL ,
	[LastModifiedDate] [datetime] NOT NULL ,
	[ETag] [nvarchar] (256) NULL ,
	[State] [int] NOT NULL 
	) ON [PRIMARY]'

	exec sp_ExecuteSQL N'ALTER TABLE [dbo].[cs_RssCtrlFeeds] ADD 
	CONSTRAINT [DF_cs_RssCtrlFeeds_Enabled] DEFAULT (1) FOR [Enabled],
	CONSTRAINT [DF_cs_RssCtrlFeeds_State] DEFAULT (0) FOR [State]'

	exec sp_ExecuteSQL N'CREATE  INDEX [IX_cs_RssCtrlFeeds] ON [dbo].[cs_RssCtrlFeeds]([CtrlID]) ON [PRIMARY]'
end

if not exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_RssCtrlPost]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
begin
	exec sp_ExecuteSQL N'CREATE TABLE [dbo].[cs_RssCtrlPost] (
	[PostID] [int] IDENTITY (1, 1) NOT NULL ,
	[CtrlID] [int] NOT NULL ,
	[UrlID] [int] NOT NULL ,
	[Author] [nvarchar] (256) NOT NULL ,
	[Subject] [nvarchar] (256) NULL ,
	[Body] [ntext] NULL ,
	[PostDate] [datetime] NOT NULL ,
	[PermaLink] [nvarchar] (312) NOT NULL ,
	[CommentUrl] [nvarchar] (512) NULL ,
	[CommentCount] [int] NULL ,
	[GuidName] [nvarchar] (512) NULL ,
	[GuidIsPermaLink] [bit] NOT NULL 
	) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]'

	exec sp_ExecuteSQL N'CREATE  UNIQUE  INDEX [IX_cs_RssCtrlPost] ON [dbo].[cs_RssCtrlPost]([PostID]) ON [PRIMARY]'

	exec sp_ExecuteSQL N'CREATE  INDEX [IX_cs_RssCtrlPost_1] ON [dbo].[cs_RssCtrlPost]([CtrlID]) ON [PRIMARY]'

	-- Index is too big for SQL2000 
	--exec sp_ExecuteSQL N'CREATE  UNIQUE  INDEX [IX_cs_RssCtrlPost_2] ON [dbo].[cs_RssCtrlPost]([PermaLink]) ON [PRIMARY]'
end

if not exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_RssCtrlUrls]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
begin
	exec sp_ExecuteSQL N'CREATE TABLE [dbo].[cs_RssCtrlUrls] (
	[UrlID] [int] IDENTITY (1, 1) NOT NULL ,
	[Url] [nvarchar] (512) NOT NULL 
	) ON [PRIMARY]'

	exec sp_ExecuteSQL N'CREATE  UNIQUE  INDEX [IX_cs_RssCtrlUrls] ON [dbo].[cs_RssCtrlUrls]([UrlID]) ON [PRIMARY]'
end
***********************************************************************************************************************************/

--## END Schema Patch ##
Insert into cs_SchemaVersion(Major, Minor, Patch, InstallDate) values (@Major, @Minor, @Patch, GetDate())

Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was applied successfully '

	END
ELSE IF(@Installed is not null)
	BEGIN
Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was already applied on ' + Convert(varchar(50), @Installed)  
	END 
ELSE
	BEGIN
Print 'The patch could not be applied because your current schema is missing previous updates (Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ')' 
	END
/***********************************************
* Patch: cs_Schema_Patch_2.1.16
* File Date: 11/29/2006 10:07:18 AM
***********************************************/
Print 'Creating...cs_Schema_Patch_2.1.16'

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

DECLARE @Major int, @Minor int, @Patch int, @Installed DateTime, @Prereqs int

Set @Major = 2;
Set @Minor = 1;
Set @Patch = 16;

Select @Prereqs = isnull(Count(InstallDate),0)  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch<@Patch

Select @Installed = InstallDate  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch=@Patch

If(@Installed is null AND @Prereqs = @Patch)
	BEGIN
--## Schema Patch ##

DECLARE @TABLE_SCHEMA NVARCHAR(50),@TABLE_NAME NVARCHAR(50),@COLUMN_NAME NVARCHAR(50),@CONSTRAINT_NAME NVARCHAR(50)

SET @TABLE_SCHEMA = 'dbo'
SET @TABLE_NAME = 'cs_RollerBlogFeeds'
SET @COLUMN_NAME = 'IsRollerBlogAggregated'

SELECT
	@CONSTRAINT_NAME = OBJECT_NAME(c1.cdefault)
FROM syscolumns AS c1 
		JOIN syscomments AS c2 
			ON c1.cdefault = c2.id 
WHERE 	OBJECT_NAME(c1.id) = @TABLE_NAME AND c1.name = @COLUMN_NAME 

/* the following does the same thing but is SQL 2005 only
select 
	@CONSTRAINT_NAME = d.name
  from sys.default_constraints as d
  join sys.objects as o
    on o.object_id = d.parent_object_id
  join sys.columns as c
    on c.object_id = o.object_id and c.column_id = d.parent_column_id
  join sys.schemas as s
    on s.schema_id = o.schema_id
WHERE s.name = @TABLE_SCHEMA and o.name = @TABLE_NAME and c.name = @COLUMN_NAME
*/

DECLARE @STRSQL NVARCHAR(4000);
if @CONSTRAINT_NAME is not null
BEGIN
    SELECT @STRSQL = N'ALTER TABLE [' + @TABLE_SCHEMA + '].['+ @TABLE_NAME +'] DROP CONSTRAINT ['+@CONSTRAINT_NAME+']'
	exec sp_ExecuteSQL @STRSQL
END
if exists (select * from dbo.sysobjects where id = object_id(N'[' + @TABLE_SCHEMA + '].['+ @TABLE_NAME +']') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
    SELECT @STRSQL = N'ALTER TABLE [' + @TABLE_SCHEMA + '].['+ @TABLE_NAME +'] DROP COLUMN ['+@COLUMN_NAME+']'
	exec sp_ExecuteSQL @STRSQL
END
--## END Schema Patch ##
Insert into cs_SchemaVersion(Major, Minor, Patch, InstallDate) values (@Major, @Minor, @Patch, GetDate())

Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was applied successfully '

	END
ELSE IF(@Installed is not null)
	BEGIN
Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was already applied on ' + Convert(varchar(50), @Installed)  
	END 
ELSE
	BEGIN
Print 'The patch could not be applied because your current schema is missing previous updates (Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ')' 
	END

/***********************************************
* Patch: cs_Schema_Patch_2.1.17
* File Date: 11/29/2006 10:07:18 AM
***********************************************/
Print 'Creating...cs_Schema_Patch_2.1.17'

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

DECLARE @Major int, @Minor int, @Patch int, @Installed DateTime, @Prereqs int

Set @Major = 2;
Set @Minor = 1;
Set @Patch = 17;

Select @Prereqs = isnull(Count(InstallDate),0)  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch<@Patch

Select @Installed = InstallDate  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch=@Patch

If(@Installed is null AND @Prereqs = @Patch)
	BEGIN
--## Schema Patch ##

-- patch sql removed, but left in so versions won't cause errors

--## END Schema Patch ##
Insert into cs_SchemaVersion(Major, Minor, Patch, InstallDate) values (@Major, @Minor, @Patch, GetDate())

Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was applied successfully '

	END
ELSE IF(@Installed is not null)
	BEGIN
Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was already applied on ' + Convert(varchar(50), @Installed)  
	END 
ELSE
	BEGIN
Print 'The patch could not be applied because your current schema is missing previous updates (Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ')' 
	END

/***********************************************
* Patch: cs_Schema_Patch_2.1.18
* File Date: 11/29/2006 10:07:19 AM
***********************************************/
Print 'Creating...cs_Schema_Patch_2.1.18'

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

DECLARE @Major int, @Minor int, @Patch int, @Installed DateTime, @Prereqs int

Set @Major = 2;
Set @Minor = 1;
Set @Patch = 18;

Select @Prereqs = isnull(Count(InstallDate),0)  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch<@Patch

Select @Installed = InstallDate  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch=@Patch

If(@Installed is null AND @Prereqs = @Patch)
	BEGIN
--## Schema Patch ##
/*****************************************  This has been moved to an addon ********************************************

IF  EXISTS (SELECT * FROM sysindexes WHERE id = OBJECT_ID(N'[dbo].[cs_RssCtrlPost]') AND name = N'IX_cs_RssCtrlPost_2')
	exec sp_ExecuteSQL N'DROP INDEX [dbo].[cs_RssCtrlPost].[IX_cs_RssCtrlPost_2]'
	
*****************************************  This has been moved to an addon ********************************************/
--## END Schema Patch ##
Insert into cs_SchemaVersion(Major, Minor, Patch, InstallDate) values (@Major, @Minor, @Patch, GetDate())

Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was applied successfully '

	END
ELSE IF(@Installed is not null)
	BEGIN
Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was already applied on ' + Convert(varchar(50), @Installed)  
	END 
ELSE
	BEGIN
Print 'The patch could not be applied because your current schema is missing previous updates (Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ')' 
	END

/***********************************************
* Patch: cs_Schema_Patch_2.1.19
* File Date: 11/29/2006 10:07:19 AM
***********************************************/
Print 'Creating...cs_Schema_Patch_2.1.19'

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

DECLARE @Major int, @Minor int, @Patch int, @Installed DateTime, @Prereqs int

Set @Major = 2;
Set @Minor = 1;
Set @Patch = 19;

Select @Prereqs = isnull(Count(InstallDate),0)  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch<@Patch

Select @Installed = InstallDate  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch=@Patch

If(@Installed is null AND @Prereqs = @Patch)
	BEGIN
--## Schema Patch ##

-- Polls (within forums)
exec sp_ExecuteSQL N'UPDATE cs_Posts SET PostMedia = 8 WHERE PostType = 2 OR (ApplicationPostType = 2 and SectionID in (select SectionID from cs_Sections where ApplicationType = 0))' 

--## END Schema Patch ##
Insert into cs_SchemaVersion(Major, Minor, Patch, InstallDate) values (@Major, @Minor, @Patch, GetDate())

Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was applied successfully '

	END
ELSE IF(@Installed is not null)
	BEGIN
Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was already applied on ' + Convert(varchar(50), @Installed)  
	END 
ELSE
	BEGIN
Print 'The patch could not be applied because your current schema is missing previous updates (Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ')' 
	END

/***********************************************
* Patch: cs_Schema_Patch_2.1.20
* File Date: 11/29/2006 10:07:18 AM
***********************************************/
Print 'Creating...cs_Schema_Patch_2.1.20'

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

DECLARE @Major int, @Minor int, @Patch int, @Installed DateTime, @Prereqs int

Set @Major = 2;
Set @Minor = 1;
Set @Patch = 20;

Select @Prereqs = isnull(Count(InstallDate),0)  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch<@Patch

Select @Installed = InstallDate  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch=@Patch

If(@Installed is null AND @Prereqs = @Patch)
	BEGIN
--## Schema Patch ##

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[PK_cs_PostReindexQueue]') and OBJECTPROPERTY(id, N'IsPrimaryKey') = 1)
exec sp_ExecuteSQL N'ALTER TABLE [dbo].[cs_PostReindexQueue] DROP CONSTRAINT [PK_cs_PostReindexQueue]'

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_PostReindexQueue]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
exec sp_ExecuteSQL N'DROP TABLE [dbo].[cs_PostReindexQueue]'

--## END Schema Patch ##
Insert into cs_SchemaVersion(Major, Minor, Patch, InstallDate) values (@Major, @Minor, @Patch, GetDate())

Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was applied successfully '

	END
ELSE IF(@Installed is not null)
	BEGIN
Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was already applied on ' + Convert(varchar(50), @Installed)  
	END 
ELSE
	BEGIN
Print 'The patch could not be applied because your current schema is missing previous updates (Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ')' 
	END

/***********************************************
* Patch: cs_Schema_Patch_2.1.21
* File Date: 11/29/2006 10:07:18 AM
***********************************************/
Print 'Creating...cs_Schema_Patch_2.1.21'

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

DECLARE @Major int, @Minor int, @Patch int, @Installed DateTime, @Prereqs int

Set @Major = 2;
Set @Minor = 1;
Set @Patch = 21;

Select @Prereqs = isnull(Count(InstallDate),0)  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch<@Patch

Select @Installed = InstallDate  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch=@Patch

If(@Installed is null AND @Prereqs = @Patch)
	BEGIN
--## Schema Patch ##

exec sp_ExecuteSQL N'ALTER TABLE [dbo].[cs_UserProfile] ADD AllowSiteToContact bit NOT NULL CONSTRAINT DF_cs_UserProfile_AllowSiteToContact DEFAULT 0'
exec sp_ExecuteSQL N'ALTER TABLE [dbo].[cs_UserProfile] ADD AllowSitePartnersToContact bit NOT NULL CONSTRAINT DF_cs_UserProfile_AllowSitePartnersToContact DEFAULT 0'

--## END Schema Patch ##
Insert into cs_SchemaVersion(Major, Minor, Patch, InstallDate) values (@Major, @Minor, @Patch, GetDate())

Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was applied successfully '

	END
ELSE IF(@Installed is not null)
	BEGIN
Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was already applied on ' + Convert(varchar(50), @Installed)  
	END 
ELSE
	BEGIN
Print 'The patch could not be applied because your current schema is missing previous updates (Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ')' 
	END
/***********************************************
* Patch: cs_Schema_Patch_2.1.22
* File Date: 11/29/2006 10:07:18 AM
***********************************************/
Print 'Creating...cs_Schema_Patch_2.1.22'

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

DECLARE @Major int, @Minor int, @Patch int, @Installed DateTime, @Prereqs int

Set @Major = 2;
Set @Minor = 1;
Set @Patch = 22;

Select @Prereqs = isnull(Count(InstallDate),0)  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch<@Patch

Select @Installed = InstallDate  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch=@Patch

If(@Installed is null AND @Prereqs = @Patch)
	BEGIN
--## Schema Patch ##

exec sp_ExecuteSQL N'ALTER TABLE [dbo].[cs_RollerBlogFeeds] ADD [SiteUrl] [nvarchar] (512) NULL'

exec sp_ExecuteSQL N'UPDATE [dbo].[cs_RollerBlogFeeds] Set SiteUrl = '''''

exec sp_ExecuteSQL N'ALTER TABLE [dbo].[cs_RollerBlogFeeds] ALTER COLUMN [SiteUrl] [nvarchar] (512) NOT NULL'


--## END Schema Patch ##
Insert into cs_SchemaVersion(Major, Minor, Patch, InstallDate) values (@Major, @Minor, @Patch, GetDate())

Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was applied successfully '

	END
ELSE IF(@Installed is not null)
	BEGIN
Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was already applied on ' + Convert(varchar(50), @Installed)  
	END 
ELSE
	BEGIN
Print 'The patch could not be applied because your current schema is missing previous updates (Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ')' 
	END

/***********************************************
* Patch: cs_Schema_Patch_2.1.23
* File Date: 11/29/2006 10:07:18 AM
***********************************************/
Print 'Creating...cs_Schema_Patch_2.1.23'

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

DECLARE @Major int, @Minor int, @Patch int, @Installed DateTime, @Prereqs int

Set @Major = 2;
Set @Minor = 1;
Set @Patch = 23;

Select @Prereqs = isnull(Count(InstallDate),0)  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch<@Patch

Select @Installed = InstallDate  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch=@Patch

If(@Installed is null AND @Prereqs = @Patch)
	BEGIN
--## Schema Patch ##

exec sp_ExecuteSQL N'Update cs_Posts set PostConfiguration = 55 from cs_Posts join cs_RollerBlogPost on cs_Posts.PostID  = cs_RollerBlogPost.PostID where PostConfiguration & 16 <> 16'

--## END Schema Patch ##
Insert into cs_SchemaVersion(Major, Minor, Patch, InstallDate) values (@Major, @Minor, @Patch, GetDate())

Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was applied successfully '

	END
ELSE IF(@Installed is not null)
	BEGIN
Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was already applied on ' + Convert(varchar(50), @Installed)  
	END 
ELSE
	BEGIN
Print 'The patch could not be applied because your current schema is missing previous updates (Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ')' 
	END

/***********************************************
* Patch: cs_Schema_Patch_2.1.24
* File Date: 11/29/2006 10:07:18 AM
***********************************************/
Print 'Creating...cs_Schema_Patch_2.1.24'

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

DECLARE @Major int, @Minor int, @Patch int, @Installed DateTime, @Prereqs int

Set @Major = 2;
Set @Minor = 1;
Set @Patch = 24;

Select @Prereqs = isnull(Count(InstallDate),0)  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch<@Patch

Select @Installed = InstallDate  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch=@Patch

If(@Installed is null AND @Prereqs = @Patch)
	BEGIN
--## Schema Patch ##
/*****************************************  This has been moved to an addon ********************************************

exec sp_ExecuteSQL N'ALTER TABLE [dbo].[cs_RssCtrlFeeds] ADD [SiteUrl] [nvarchar] (512) NULL'

exec sp_ExecuteSQL N'UPDATE [dbo].[cs_RssCtrlFeeds] Set SiteUrl = '''''

exec sp_ExecuteSQL N'ALTER TABLE [dbo].[cs_RssCtrlFeeds] ALTER COLUMN [SiteUrl] [nvarchar] (512) NOT NULL'

exec sp_ExecuteSQL N'ALTER TABLE [dbo].[cs_RssCtrl] ADD [SettingsID] [int] NULL'

exec sp_ExecuteSQL N'UPDATE [dbo].[cs_RssCtrl] Set [SettingsID] = (select min(SettingsID) from cs_SiteSettings)'

exec sp_ExecuteSQL N'ALTER TABLE [dbo].[cs_RssCtrl] ALTER COLUMN [SettingsID] [int] NOT NULL'

exec sp_ExecuteSQL N'ALTER TABLE [dbo].[cs_RssCtrlFeeds] ADD [IntervalMinutes] [int] NULL'

exec sp_ExecuteSQL N'UPDATE [dbo].[cs_RssCtrlFeeds] Set [IntervalMinutes] = 5'

exec sp_ExecuteSQL N'ALTER TABLE [dbo].[cs_RssCtrlFeeds] ALTER COLUMN [IntervalMinutes] [int] NOT NULL'

*****************************************  This has been moved to an addon ********************************************/
--## END Schema Patch ##
Insert into cs_SchemaVersion(Major, Minor, Patch, InstallDate) values (@Major, @Minor, @Patch, GetDate())

Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was applied successfully '

	END
ELSE IF(@Installed is not null)
	BEGIN
Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was already applied on ' + Convert(varchar(50), @Installed)  
	END 
ELSE
	BEGIN
Print 'The patch could not be applied because your current schema is missing previous updates (Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ')' 
	END

/***********************************************
* Patch: cs_Schema_Patch_2.1.25
* File Date: 11/29/2006 10:07:18 AM
***********************************************/
Print 'Creating...cs_Schema_Patch_2.1.25'

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

DECLARE @Major int, @Minor int, @Patch int, @Installed DateTime, @Prereqs int

Set @Major = 2;
Set @Minor = 1;
Set @Patch = 25;

Select @Prereqs = isnull(Count(InstallDate),0)  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch<@Patch

Select @Installed = InstallDate  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch=@Patch

If(@Installed is null AND @Prereqs = @Patch)
	BEGIN
--## Schema Patch ##

exec sp_ExecuteSQL N'Alter Table cs_Posts Add  SpamScore [int] Not Null Constraint cs_Posts_DefaultSpamScore default(0)'

exec sp_ExecuteSQL N'Alter Table cs_Posts Add  PostStatus [int] Not Null Constraint cs_Posts_DefaultPostStatus default(0)'

--## END Schema Patch ##
Insert into cs_SchemaVersion(Major, Minor, Patch, InstallDate) values (@Major, @Minor, @Patch, GetDate())

Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was applied successfully '

	END
ELSE IF(@Installed is not null)
	BEGIN
Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was already applied on ' + Convert(varchar(50), @Installed)  
	END 
ELSE
	BEGIN
Print 'The patch could not be applied because your current schema is missing previous updates (Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ')' 
	END

/***********************************************
* Patch: cs_Schema_Patch_2.1.26
* File Date: 11/29/2006 10:07:18 AM
***********************************************/
Print 'Creating...cs_Schema_Patch_2.1.26'

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

DECLARE @Major int, @Minor int, @Patch int, @Installed DateTime, @Prereqs int

Set @Major = 2;
Set @Minor = 1;
Set @Patch = 26;

Select @Prereqs = isnull(Count(InstallDate),0)  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch<@Patch

Select @Installed = InstallDate  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch=@Patch

If(@Installed is null AND @Prereqs = @Patch)
	BEGIN
--## Schema Patch ##

exec sp_ExecuteSQL N'update cs_Posts set PostMedia = 2 where SectionID in (select SectionID from cs_Sections where ApplicationType = 1) and ApplicationPostType in (1, 2) and PropertyNames like ''%VideoUrl%'''

--## END Schema Patch ##
Insert into cs_SchemaVersion(Major, Minor, Patch, InstallDate) values (@Major, @Minor, @Patch, GetDate())

Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was applied successfully '

	END
ELSE IF(@Installed is not null)
	BEGIN
Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was already applied on ' + Convert(varchar(50), @Installed)  
	END 
ELSE
	BEGIN
Print 'The patch could not be applied because your current schema is missing previous updates (Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ')' 
	END 


/***********************************************
* Patch: cs_Schema_Patch_2.1.27
* File Date: 11/29/2006 10:07:19 AM
***********************************************/
Print 'Creating...cs_Schema_Patch_2.1.27'

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

DECLARE @Major int, @Minor int, @Patch int, @Installed DateTime, @Prereqs int

Set @Major = 2;
Set @Minor = 1;
Set @Patch = 27;

Select @Prereqs = isnull(Count(InstallDate),0)  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch<@Patch

Select @Installed = InstallDate  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch=@Patch

If(@Installed is null AND @Prereqs = @Patch)
	BEGIN
--## Schema Patch ##


UPDATE	PP
SET		PP.AllowMask = CONVERT(bigint, PP.AllowMask) | CONVERT(bigint, 0x0000000000000100)
FROM	cs_ProductPermissions PP INNER JOIN aspnet_Roles R ON PP.RoleID = R.RoleId
WHERE	ApplicationType = 0 AND R.LoweredRoleName IN ('moderator', 'forumsadministrator', 'systemadministrator')


--## END Schema Patch ##
Insert into cs_SchemaVersion(Major, Minor, Patch, InstallDate) values (@Major, @Minor, @Patch, GetDate())

Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was applied successfully '

	END
ELSE IF(@Installed is not null)
	BEGIN
Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was already applied on ' + Convert(varchar(50), @Installed)  
	END 
ELSE
	BEGIN
Print 'The patch could not be applied because your current schema is missing previous updates (Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ')' 
	END 


/***********************************************
* Patch: cs_Schema_Patch_2.1.28
* File Date: 11/29/2006 10:07:19 AM
***********************************************/
Print 'Creating...cs_Schema_Patch_2.1.28'

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

DECLARE @Major int, @Minor int, @Patch int, @Installed DateTime, @Prereqs int

Set @Major = 2;
Set @Minor = 1;
Set @Patch = 28;

Select @Prereqs = isnull(Count(InstallDate),0)  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch<@Patch

Select @Installed = InstallDate  from cs_SchemaVersion where Major=@Major and Minor=@Minor and Patch=@Patch

If(@Installed is null AND @Prereqs = @Patch)
	BEGIN
--## Schema Patch ##

exec sp_ExecuteSQL N'Alter Table cs_posts_deleted_archive Add PropertyNames [ntext] NULL'
exec sp_ExecuteSQL N'Alter Table cs_posts_deleted_archive Add PropertyValues [ntext] NULL'
exec sp_ExecuteSQL N'Alter Table cs_posts_deleted_archive Add SpamScore [int] NULL'
exec sp_ExecuteSQL N'Alter Table cs_posts_deleted_archive Add PostStatus [int] NULL'


--## END Schema Patch ##
Insert into cs_SchemaVersion(Major, Minor, Patch, InstallDate) values (@Major, @Minor, @Patch, GetDate())

Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was applied successfully '

	END
ELSE IF(@Installed is not null)
	BEGIN
Print 'Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ' was already applied on ' + Convert(varchar(50), @Installed)  
	END 
ELSE
	BEGIN
Print 'The patch could not be applied because your current schema is missing previous updates (Schema Patch v' + Convert(Varchar(2),@Major) + '.' + Convert(Varchar(2),@Minor) + '.' +  Convert(Varchar(3),@Patch) + ')' 
	END 


/***********************************************
* View: cs_vw_EveryOne_Role
* File Date: 11/29/2006 10:07:36 AM
***********************************************/
Print 'Creating...cs_vw_EveryOne_Role'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO


if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_vw_EveryOne_Role]') and OBJECTPROPERTY(id, N'IsView') = 1)
drop view [dbo].[cs_vw_EveryOne_Role]
GO

CREATE View [dbo].cs_vw_EveryOne_Role
as

SELECT jA.LoweredApplicationName, jA.[ApplicationId], [RoleId], [RoleName], [LoweredRoleName], aspnet_Roles.[Description] 

FROM [aspnet_Roles]
JOIN aspnet_Applications jA on aspnet_Roles.ApplicationId = jA.ApplicationId

Where LoweredRoleName = 'everyone'












GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant select on [dbo].[cs_vw_EveryOne_Role] to public
/***********************************************
* View: cs_vw_HasReadForum
* File Date: 11/29/2006 10:07:36 AM
***********************************************/
Print 'Creating...cs_vw_HasReadForum'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_vw_HasReadForum]') and OBJECTPROPERTY(id, N'IsView') = 1)
drop view [dbo].[cs_vw_HasReadForum]
GO

Create View [dbo].cs_vw_HasReadForum

as
Select UserID, SectionID, MarkReadAfter, null as ThreadID, LastActivity FROM cs_SectionsRead 
Union
Select UserID, SectionID, null, ThreadID, null FROM cs_ThreadsRead


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant select on [dbo].[cs_vw_HasReadForum] to public
/***********************************************
* View: cs_vw_PostsWithAttachmentDetails
* File Date: 11/29/2006 10:07:37 AM
***********************************************/
Print 'Creating...cs_vw_PostsWithAttachmentDetails'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_vw_PostsWithAttachmentDetails]') and OBJECTPROPERTY(id, N'IsView') = 1)
drop view [dbo].[cs_vw_PostsWithAttachmentDetails]
GO

Create View [dbo].cs_vw_PostsWithAttachmentDetails
as

SELECT 
	p.[PostID], p.[ThreadID], p.[ParentID], p.[PostAuthor], p.[UserID], p.[SectionID], 
	p.[PostLevel], p.[SortOrder], p.[Subject], p.[PostDate], p.[IsApproved], p.[IsLocked], 
	p.[TotalViews], p.[Body], p.[FormattedBody], p.[IPAddress], p.[PostType], p.[PostMedia], p.[EmoticonID], 
	p.[PropertyNames] as PostPropertyNames, p.[PropertyValues] as PostPropertyValues, p.[SettingsID], p.[AggViews], p.[PostConfiguration], 
	p.[isIndexed], p.[PostName], p.[UserTime], p.[ApplicationPostType], p.[Points], p.[RatingSum], 
	p.[TotalRatings], pa.[FileName] as AttachmentFilename, pa.[FileName], pa.[ContentType], pa.[ContentSize], pa.[Height], pa.[Width], pa.[IsRemote], pa.[FriendlyFileName], pa.Created,
	p.PostStatus, p.SpamScore

FROM cs_Posts p (nolock)
LEFT JOIN cs_PostAttachments pa (nolock) on p.PostID = pa.PostID



GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO


--Select * FROM cs_vw_PostsWithAttachmentDetails

grant select on [dbo].[cs_vw_PostsWithAttachmentDetails] to public



/***********************************************
* View: cs_vw_UsersInRoles
* File Date: 11/29/2006 10:07:36 AM
***********************************************/
Print 'Creating...cs_vw_UsersInRoles'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_vw_UsersInRoles]') and OBJECTPROPERTY(id, N'IsView') = 1)
drop view [dbo].[cs_vw_UsersInRoles]
GO

CREATE VIEW [dbo].cs_vw_UsersInRoles
AS

SELECT 
	cu.UserID, ur.RoleId
FROM
	aspnet_UsersInRoles ur (nolock)
	INNER JOIN aspnet_Users au (nolock) on au.UserId = ur.UserId
	INNER JOIN cs_Users cu (nolock) on au.UserId = cu.MembershipID

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant select on [dbo].[cs_vw_UsersInRoles] to public



/***********************************************
* View: cs_vw_Users_FullUser
* File Date: 11/29/2006 10:07:36 AM
***********************************************/
Print 'Creating...cs_vw_Users_FullUser'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_vw_Users_FullUser]') and OBJECTPROPERTY(id, N'IsView') = 1)
drop view [dbo].[cs_vw_Users_FullUser]
GO

Create View [dbo].cs_vw_Users_FullUser
as

Select 
	au.UserName, au.IsAnonymous, au.UserId, au.LastActivityDate,
	am.PasswordQuestion, am.Email, am.IsApproved,am.CreateDate, am.LastLoginDate, am.LastPasswordChangedDate, am.IsLockedOut, am.LastLockoutDate,
	am.Comment, cu.UserID as cs_UserID, cu.ForceLogin as cs_ForceLogin, cu.UserAccountStatus as cs_UserAccountStatus, cu.AppUserToken as cs_AppUserToken, am.PasswordFormat,
	cu.LastActivity as cs_LastActivity, cu.LastAction as cs_LastAction, fup.IsIgnored,fup.PublicToken,
	fup.TimeZone, fup.TotalPosts, fup.PostSortOrder, fup.PropertyNames as UserPropertyNames, fup.PropertyValues as UserPropertyValues, fup.PostRank, fup.IsAvatarApproved, fup.ModerationLevel, 
	fup.EnableThreadTracking, fup.EnableDisplayUnreadThreadsOnly, fup.EnableAvatar, fup.EnableDisplayInMemberList, fup.EnablePrivateMessages, 
	fup.EnableOnlineStatus, fup.EnableEmail, fup.EnableHtmlEmail, fup.SettingsID, ap.PropertyNames as ProfileNames, ap.PropertyValuesString, ap.PropertyValuesBinary,
	fup.Points as UserPoints, fup.FavoritesShared, fup.AllowSiteToContact, fup.AllowSitePartnersToContact
From
	aspnet_Membership  am (nolock)

INNER JOIN aspnet_Users au (nolock) on am.UserId = au.UserId
INNER JOIN cs_Users cu (nolock) on au.UserId = cu.MembershipID
INNER JOIN cs_UserProfile  fup (nolock) on cu.UserID = fup.UserID
LEFT  JOIN aspnet_Profile ap (nolock) on au.UserId = ap.UserId


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO


--Select * FROM cs_vw_Users_FullUser

grant select on [dbo].[cs_vw_Users_FullUser] to public



/***********************************************
* Sproc: csm_EmailIDs_FindUserEmailID
* File Date: 11/29/2006 10:07:30 AM
***********************************************/
Print 'Creating...csm_EmailIDs_FindUserEmailID'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[csm_EmailIDs_FindUserEmailID]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
	drop procedure [csm_EmailIDs_FindUserEmailID]
GO

CREATE PROCEDURE dbo.csm_EmailIDs_FindUserEmailID
	@EmailID bigint
AS

select E.UserID, E.SectionID, S.SettingsID
 from csm_EmailIDs E
 left join cs_Sections S on (S.SectionID = E.SectionID)
 where EmailID = @EmailID
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [csm_EmailIDs_FindUserEmailID] to public
go
/***********************************************
* Sproc: csm_EmailIDs_GetUserEmailID
* File Date: 11/29/2006 10:07:31 AM
***********************************************/
Print 'Creating...csm_EmailIDs_GetUserEmailID'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[csm_EmailIDs_GetUserEmailID]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
	drop procedure [csm_EmailIDs_GetUserEmailID]
GO

CREATE PROCEDURE dbo.csm_EmailIDs_GetUserEmailID
	@UserID int,
	@SectionID int,
	@SettingsID int
AS

select EmailID from csm_EmailIDs where UserID = @UserID and SectionID = @SectionID
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [csm_EmailIDs_GetUserEmailID] to public
go
/***********************************************
* Sproc: csm_EmailIDs_UpdateUserEmailID
* File Date: 11/29/2006 10:07:30 AM
***********************************************/
Print 'Creating...csm_EmailIDs_UpdateUserEmailID'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[csm_EmailIDs_UpdateUserEmailID]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
	drop procedure [csm_EmailIDs_UpdateUserEmailID]
GO

CREATE PROCEDURE dbo.csm_EmailIDs_UpdateUserEmailID
	@EmailID bigint,
	@UserID int,
	@SectionID int,
	@SettingsID int
AS

delete from csm_EmailIDs where UserID = @UserID and SectionID = @SectionID

insert into csm_EmailIDs (EmailID, UserID, SectionID) values (@EmailID, @UserID, @SectionID)
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [csm_EmailIDs_UpdateUserEmailID] to public
go
/***********************************************
* Sproc: csm_MailingLists_CreateUpdate
* File Date: 11/29/2006 10:07:31 AM
***********************************************/
Print 'Creating...csm_MailingLists_CreateUpdate'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[csm_MailingLists_CreateUpdate]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
	drop procedure [csm_MailingLists_CreateUpdate]
GO

CREATE PROCEDURE [dbo].csm_MailingLists_CreateUpdate
(
	@SectionID		int,
	@EmailAddress		nvarchar(100),
	@IsMailingList		bit,
	@SettingsID		int
)
AS

if exists(select [SectionID] from csm_MailingLists where SectionID = @SectionID and SettingsID = @SettingsID)
begin
	update csm_MailingLists set EmailAddress = @EmailAddress, IsMailingList = @IsMailingList where SectionID = @SectionID and SettingsID = @SettingsID
end
else
begin
	insert into csm_MailingLists (SectionID, EmailAddress, IsMailingList, SettingsID) values (@SectionID, @EmailAddress, @IsMailingList, @SettingsID)
end

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [csm_MailingLists_CreateUpdate] to public
go
/***********************************************
* Sproc: csm_MailingLists_Get
* File Date: 11/29/2006 10:07:32 AM
***********************************************/
Print 'Creating...csm_MailingLists_Get'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[csm_MailingLists_Get]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
	drop procedure [csm_MailingLists_Get]
GO

CREATE PROCEDURE [dbo].csm_MailingLists_Get
(
	@SettingsID		int
)
AS
SET Transaction Isolation Level Read UNCOMMITTED

-- Return all the sections that are mailing lists
SELECT
	F.SectionID, F.SettingsID, F.IsActive, F.ParentID, F.GroupID, F.Name, F.NewsgroupName, F.Description, F.DateCreated, F.Url, F.IsModerated,
	F.DaysToView, F.SortOrder, F.TotalPosts, F.TotalThreads, F.DisplayMask, F.EnablePostStatistics, F.EnableAutoDelete, F.EnableAnonymousPosting,
	F.AutoDeleteThreshold, F.MostRecentPostID, F.MostRecentThreadID, F.MostRecentThreadReplies, F.MostRecentPostSubject, F.MostRecentPostAuthor,
	F.MostRecentPostAuthorID, F.MostRecentPostDate, F.PostsToModerate, F.ForumType, F.IsSearchable, F.ApplicationType, F.ApplicationKey, F.Path,
	F.PropertyNames as SectionPropertyNames, F.PropertyValues as SectionPropertyValues,
	M.EmailAddress, M.IsMailingList
FROM
	csm_MailingLists M
LEFT JOIN cs_Sections F ON F.SectionID = M.SectionID
WHERE
	M.SettingsID = @SettingsID

exec csm_MailingList_Permissions_Get @SettingsID

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [csm_MailingLists_Get] to public
go
/***********************************************
* Sproc: csm_MailingList_Permissions_Get
* File Date: 11/29/2006 10:07:31 AM
***********************************************/
Print 'Creating...csm_MailingList_Permissions_Get'

-- exec cs_Section_Permissions_Get 1000, 0
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from sysobjects where id = object_id(N'[dbo].[csm_MailingList_Permissions_Get]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[csm_MailingList_Permissions_Get]
GO

create procedure [dbo].csm_MailingList_Permissions_Get
(
	@SettingsID int
)
AS

SET Transaction Isolation Level Read UNCOMMITTED

	-- Return product permissions
	SELECT
		P.SettingsID, 
		Implied = convert(bit, 1), 
		SectionID = -1,
		EmailAddress = null,
		ApplicationKey = null,
		R.RoleName, 
		P.RoleID, 
		P.ApplicationType,
		AllowMask = convert(bigint, coalesce(P.AllowMask, 0x00)), 
		DenyMask = convert(bigint, coalesce(P.DenyMask, 0x00))
	FROM
		cs_ProductPermissions P,
		aspnet_Roles R
	WHERE 
		P.RoleID = R.RoleId AND
		P.SettingsID = @SettingsID

	UNION

	-- Return section permissions
	SELECT
		P.SettingsID, 
		Implied = convert(bit, 0), 
		P.SectionID, 
		M.EmailAddress,
		F.ApplicationKey,
		R.RoleName, 
		P.RoleID, 
		F.ApplicationType,
		AllowMask = convert(bigint, coalesce(P.AllowMask, 0x00)),  
		DenyMask = convert(bigint, coalesce(P.DenyMask, 0x00))  
	FROM 
		cs_sectionpermissions P,
		aspnet_Roles r,
		csm_MailingLists M,
		cs_Sections F
	WHERE
		P.RoleID = r.RoleId AND
		P.SettingsID = @SettingsID AND
		P.SectionID = M.SectionID AND
		F.SectionID = M.SectionID AND
		M.IsMailingList = 1

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[csm_MailingList_Permissions_Get] to public
go
/***********************************************
* Sproc: csm_Post_FindPostParent
* File Date: 11/29/2006 10:07:30 AM
***********************************************/
Print 'Creating...csm_Post_FindPostParent'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[csm_Post_FindPostParent]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
	drop procedure [csm_Post_FindPostParent]
GO

CREATE PROCEDURE [dbo].csm_Post_FindPostParent
(
	@PostID int=-1,
	@Subject nvarchar(256)=null,
	@SectionID int,
	@SettingsID int
)
AS
SET Transaction Isolation Level Read UNCOMMITTED

if @PostID <> -1
begin
	if exists(SELECT PostID FROM cs_Posts P WHERE P.SectionID = @SectionID AND P.SettingsID = @SettingsID AND P.PostID = @PostID)
		select @PostID as PostID
	else	select -1 as PostID
end
else
begin
	if exists(SELECT PostID FROM cs_Posts P WHERE P.SectionID = @SectionID AND P.SettingsID = @SettingsID AND P.Subject = @Subject)
		SELECT PostID FROM cs_Posts P WHERE P.SectionID = @SectionID AND P.SettingsID = @SettingsID AND P.Subject = @Subject
	else
		select -1 as PostID
end

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [csm_Post_FindPostParent] to public
go
/***********************************************
* Sproc: cs_ApplicationConfigurationSettings_CreateUpdate
* File Date: 11/29/2006 10:07:34 AM
***********************************************/
Print 'Creating...cs_ApplicationConfigurationSettings_CreateUpdate'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_ApplicationConfigurationSettings_CreateUpdate]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_ApplicationConfigurationSettings_CreateUpdate]
GO



CREATE  PROCEDURE [dbo].cs_ApplicationConfigurationSettings_CreateUpdate --11, 36, 0, 1, 0
(
	@SettingsID int,
	@ApplicationType smallint,
	@Settings NText = null
)

as

if exists(Select SettingsID FROM cs_ApplicationConfigurationSettings where SettingsID = @SettingsID and ApplicationType = @ApplicationType)
Begin
	Update cs_ApplicationConfigurationSettings
	Set Settings = @Settings
	where SettingsID = @SettingsID and ApplicationType = @ApplicationType
End
Else
Begin
	Insert cs_ApplicationConfigurationSettings (SettingsID, ApplicationType, Settings) 
	Values(@SettingsID, @ApplicationType, @Settings) 
End


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_ApplicationConfigurationSettings_CreateUpdate] to public
go
/***********************************************
* Sproc: cs_ApplicationConfigurationSettings_Get
* File Date: 11/29/2006 10:07:30 AM
***********************************************/
Print 'Creating...cs_ApplicationConfigurationSettings_Get'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_ApplicationConfigurationSettings_Get]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_ApplicationConfigurationSettings_Get]
GO



CREATE  PROCEDURE [dbo].cs_ApplicationConfigurationSettings_Get --11, 36, 0, 1, 0
(
	@SettingsID int,
	@ApplicationType smallint
)
as
Select Settings FROM cs_ApplicationConfigurationSettings where SettingsID = @SettingsID and ApplicationType = @ApplicationType



GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_ApplicationConfigurationSettings_Get] to public
go
/***********************************************
* Sproc: cs_Audit_Post
* File Date: 11/29/2006 10:07:30 AM
***********************************************/
Print 'Creating...cs_Audit_Post'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Audit_Post]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Audit_Post]
GO


CREATE proc [dbo].cs_Audit_Post
(
	@PostID		int,
	@SettingsID 	int
)
AS
SET Transaction Isolation Level Read UNCOMMITTED
	-- Get the Post
	exec cs_forums_Post @PostID, null, 0, @SettingsID

	SELECT
		B.Description,
		U.UserName,
		A.*
	FROM
		cs_ModerationAudit A,
		cs_ModerationAction B,
		cs_vw_Users_FullUser U
	WHERE
		A.ModerationAction = B.ModerationAction AND
		A.SettingsID = B.SettingsID AND
		U.cs_UserID = A.ModeratorID AND
		A.PostID = @PostID AND
		A.SettingsID = @SettingsID
	ORDER BY
		ModeratedOn

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT EXECUTE on dbo.cs_Audit_Post to public
GO
/***********************************************
* Sproc: cs_BannedAddresses_Get
* File Date: 11/29/2006 10:07:30 AM
***********************************************/
Print 'Creating...cs_BannedAddresses_Get'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_BannedAddresses_Get]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_BannedAddresses_Get]
GO

CREATE Procedure [dbo].[cs_BannedAddresses_Get]
	@SettingsID	int
AS

	SELECT
		SettingsID
		, NetworkAddress
		, BannedDate
	FROM cs_BannedAddresses 
	WHERE SettingsID = @SettingsID



GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO


GRANT  EXECUTE  ON [dbo].[cs_BannedAddresses_Get]  TO [public]
GO

/***********************************************
* Sproc: cs_BannedAddress_CreateUpdateDelete
* File Date: 11/29/2006 10:07:30 AM
***********************************************/
Print 'Creating...cs_BannedAddress_CreateUpdateDelete'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_BannedAddress_CreateUpdateDelete]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_BannedAddress_CreateUpdateDelete]
GO

CREATE Procedure [dbo].[cs_BannedAddress_CreateUpdateDelete]
	  @SettingsID		INT
	, @NetworkAddress	NVARCHAR(50) 
	, @BannedDate		DATETIME
	, @ActionType		INT
AS
	DECLARE @ID INT
	DECLARE @ERROR INT
	DECLARE @ROWCOUNT INT
	
	-- CREATE
	IF @ActionType = 0 
	BEGIN
		IF EXISTS( SELECT * FROM cs_BannedAddresses where SettingsID = @SettingsID and NetworkAddress = @NetworkAddress )
			exec cs_BannedAddress_CreateUpdateDelete @SettingsID, @NetworkAddress, @BannedDate, 1 
		else
		BEGIN
		
			INSERT INTO cs_BannedAddresses VALUES( @SettingsID, @NetworkAddress, @BannedDate )

			SELECT @ERROR = @@ERROR, @ID = @@IDENTITY, @ROWCOUNT = @@ROWCOUNT
			IF( @ERROR <> 0 )
			BEGIN
				RAISERROR( 'An error occurred while trying to create a new cs_BannedAddress record.', 16, 1 )
				RETURN @ERROR
			END
			ELSE
			BEGIN
				RETURN 0
			END
		END
	END
	ELSE IF( @ActionType = 1 )
	BEGIN
		-- UPDATE
		IF NOT EXISTS( SELECT * FROM cs_BannedAddresses WHERE SettingsID = @SettingsID and NetworkAddress = @NetworkAddress )
			exec cs_BannedAddress_CreateUpdateDelete @SettingsID, @NetworkAddress, @BannedDate, 0 
		ELSE
		BEGIN
			UPDATE cs_BannedAddresses SET
				SettingsID = @SettingsID,
				NetworkAddress = @NetworkAddress,
				BannedDate = @BannedDate
			WHERE
					SettingsID = @SettingsID 
				AND NetworkAddress = @NetworkAddress
				
			SELECT @ERROR = @@ERROR, @ID = @@IDENTITY, @ROWCOUNT = @@ROWCOUNT
			IF( @ERROR <> 0 )
			BEGIN
				RAISERROR('Could not update the cs_BannedAddress record for SettingsID %d and NetworkAddress of %d', 16, 1, @SettingsID, @NetworkAddress )
				RETURN @ERROR
			END
			ELSE
			BEGIN
				RETURN 0				
			END
		END
	END
	ELSE IF( @ActionType = 2 )
	BEGIN
		-- DELETE
		DELETE cs_BannedAddresses
		WHERE SettingsID = @SettingsID
			AND NetworkAddress = @NetworkAddress
			
		SELECT @ERROR = @@ERROR, @ID = @@IDENTITY, @ROWCOUNT = @@ROWCOUNT
		IF( @ROWCOUNT = 1 )
			RETURN 0
		ELSE
			RETURN 1
		
	END
	ELSE
	BEGIN
		RAISERROR( 'The ActionType value should be between 0 and 2. The value of %d was not within this range', 16, 1, @ActionType )
		RETURN 1
	END
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO


GRANT  EXECUTE  ON [dbo].[cs_BannedAddress_CreateUpdateDelete]  TO [public]
GO

/***********************************************
* Sproc: cs_BannedNetworks_Get
* File Date: 11/29/2006 10:07:31 AM
***********************************************/
Print 'Creating...cs_BannedNetworks_Get'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_BannedNetworks_Get]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_BannedNetworks_Get]
GO

CREATE Procedure [dbo].[cs_BannedNetworks_Get]
	@SettingsID int
AS
	SELECT	SettingsID
		, BannedNetworkID
		, StartingAddress
		, EndingAddress
		, BannedDate
	FROM cs_BannedNetworks 
	WHERE SettingsID = @SettingsID


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT  EXECUTE  ON [dbo].[cs_BannedNetworks_Get]  TO [public]
GO

/***********************************************
* Sproc: cs_BannedNetwork_CreateUpdateDelete
* File Date: 11/29/2006 10:07:31 AM
***********************************************/
Print 'Creating...cs_BannedNetwork_CreateUpdateDelete'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_BannedNetwork_CreateUpdateDelete]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_BannedNetwork_CreateUpdateDelete]
GO


CREATE Procedure [dbo].[cs_BannedNetwork_CreateUpdateDelete]
	@BannedNetworkID	INT = 0 OUTPUT,
	@SettingsID			INT,
	@StartingAddress	NVARCHAR(50)=  null,
	@EndingAddress		NVARCHAR(50) = null,
	@BannedDate			DATETIME,
	@ActionType			INT
AS
	DECLARE @ID INT
	DECLARE @ERROR INT
	DECLARE @ROWCOUNT INT
	
	-- CREATE
	IF @ActionType = 0 
	BEGIN
		IF EXISTS( SELECT * FROM cs_BannedNetworks where SettingsID = @SettingsID and BannedNetworkID = @BannedNetworkID )
			exec cs_BannedNetwork_CreateUpdateDelete @BannedNetworkID OUTPUT, @SettingsID, @StartingAddress, @EndingAddress, @BannedDate, 1 
		ELSE
		BEGIN
		
			INSERT INTO cs_BannedNetworks (
				SettingsID,
				StartingAddress,
				EndingAddress,
				BannedDate
			) VALUES( 
				@SettingsID,
				@StartingAddress,
				@EndingAddress,
				@BannedDate
			)

			SELECT @ERROR = @@ERROR, @ID = @@IDENTITY, @ROWCOUNT = @@ROWCOUNT
			IF( @ERROR <> 0 )
			BEGIN
				RAISERROR( 'An error occurred while trying to create a new cs_BannedNetwork record.', 16, 1 )
				RETURN @ERROR
			END
			ELSE
			BEGIN
				SET @BannedNetworkID = @ID
				RETURN 0
			END
		END
	END
	ELSE IF( @ActionType = 1 )
	BEGIN
		-- UPDATE
		IF NOT EXISTS( SELECT * FROM cs_BannedNetworks WHERE SettingsID = @SettingsID and BannedNetworkID = @BannedNetworkID )
			exec cs_BannedNetwork_CreateUpdateDelete @BannedNetworkID OUTPUT, @SettingsID, @StartingAddress, @EndingAddress, @BannedDate, 0 
		ELSE
		BEGIN
			UPDATE cs_BannedNetworks SET
				SettingsID		= @SettingsID,
				StartingAddress	= @StartingAddress,
				EndingAddress	= @EndingAddress,
				BannedDate		= @BannedDate
			WHERE
					SettingsID		= @SettingsID 
				AND BannedNetworkID = @BannedNetworkID
				
			SELECT @ERROR = @@ERROR, @ID = @@IDENTITY, @ROWCOUNT = @@ROWCOUNT
			IF( @ERROR <> 0 )
			BEGIN
				RAISERROR('Could not update the cs_BannedNetworks record for SettingsID %d and BannedNetworkID of %d', 16, 1, @SettingsID, @BannedNetworkID )
				RETURN @ERROR
			END
			ELSE
			BEGIN
				RETURN 0				
			END
		END
	END
	ELSE IF( @ActionType = 2 )
	BEGIN
		-- DELETE
		DELETE cs_BannedNetworks
		WHERE SettingsID		= @SettingsID
			AND BannedNetworkID = @BannedNetworkID
			
		SELECT @ERROR = @@ERROR, @ID = @@IDENTITY, @ROWCOUNT = @@ROWCOUNT
		IF( @ROWCOUNT = 1 )
			RETURN 0
		ELSE
			RETURN 1
		
	END
	ELSE
	BEGIN
		RAISERROR( 'The ActionType value should be between 0 and 2. The value of %d was not within this range', 16, 1, @ActionType )
		RETURN 1
	END
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO


GRANT  EXECUTE  ON [dbo].[cs_BannedNetwork_CreateUpdateDelete]  TO [public]
GO

/***********************************************
* Sproc: cs_BlogActivityNightlyJob
* File Date: 11/29/2006 10:07:31 AM
***********************************************/
Print 'Creating...cs_BlogActivityNightlyJob'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_BlogActivityNightlyJob]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_BlogActivityNightlyJob]
GO

CREATE    PROCEDURE [dbo].cs_BlogActivityNightlyJob

AS
SET Transaction Isolation Level Read UNCOMMITTED
BEGIN
	declare @RunDate datetime
	declare @JobRunDate datetime
	set @JobRunDate = getdate()
	set @RunDate = dateadd(d, -1, convert(datetime, (convert(varchar(10), @JobRunDate, 101))))
	 
        insert into [cs_BlogActivityReport] 
	select t.SectionID, t.ThreadID, @RunDate as CoverageDate
	 ,TotalViews  = (select t1.TotalViews from dbo.cs_Threads t1 left outer join cs_BlogActivityReport yesterdays on t.ThreadID = yesterdays.ThreadID and yesterdays.CoverageDate = dateadd(d, -1, @RunDate) where t1.ThreadID = t.ThreadID and t1.SectionID = t.SectionID)
	 ,DayViews = (select coalesce((t1.TotalViews - yesterdays.TotalViews), t1.TotalViews) from dbo.cs_Threads t1 left outer join cs_BlogActivityReport yesterdays on t.ThreadID = yesterdays.ThreadID and yesterdays.CoverageDate = dateadd(d, -1, @RunDate) where t1.ThreadID = t.ThreadID and t1.SectionID = t.SectionID)
	 ,DayComments  = (select count(*) from dbo.cs_Posts p1 where p1.ThreadID = t.ThreadID and p1.PostID <> p1.ParentID and p1.ApplicationPostType = 4 and p1.PostDate between @RunDate and dateadd(d, 1, @RunDate))
	 ,DayTrackBacks = (select count(*) from dbo.cs_Posts p1 where p1.ThreadID = t.ThreadID and p1.PostID <> p1.ParentID and p1.ApplicationPostType = 8 and p1.PostDate between @RunDate and dateadd(d, 1, @RunDate))
         ,IsPost   = (select case when p1.ApplicationPostType = 1 then 1 else 0 end from dbo.cs_Posts p1 where p1.ThreadID = t.ThreadID and p1.PostID = p1.ParentID)
	 ,IsArticle  = (select case when p1.ApplicationPostType = 2 then 1 else 0 end from dbo.cs_Posts p1 where p1.ThreadID = t.ThreadID and p1.PostID = p1.ParentID)
	 ,JobExecutionTimeStamp = @JobRunDate
         ,DayPosts = (select count(*) from dbo.cs_Posts p1 where p1.ApplicationPostType = 1 and p1.ThreadID = t.ThreadID and p1.PostID = p1.ParentID and p1.PostDate between @RunDate and dateadd(d, 1, @RunDate))
	 ,DayArticles = (select count(*) from dbo.cs_Posts p1 where p1.ApplicationPostType = 2 and p1.ThreadID = t.ThreadID and p1.PostID = p1.ParentID and p1.PostDate between @RunDate and dateadd(d, 1, @RunDate))
	from dbo.cs_Threads t 
	-- Some existing CS databases have orphaned thread records that should have been deleted, so check to make sure at least one top-level post exists for the thread
	where exists(select PostID from dbo.cs_Posts p1 where p1.ThreadID = t.ThreadID and p1.PostID = p1.ParentID)

END






GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].cs_BlogActivityNightlyJob to public
go

/***********************************************
* Sproc: cs_BlogActivityReportAggregate_Get
* File Date: 11/29/2006 10:07:34 AM
***********************************************/
Print 'Creating...cs_BlogActivityReportAggregate_Get'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_BlogActivityReportAggregate_Get]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_BlogActivityReportAggregate_Get]
GO

CREATE      PROCEDURE [dbo].cs_BlogActivityReportAggregate_Get
(
	 @nRecordNumberStart INT
    	,@nRecordNumberEnd INT
        ,@BegReportDate DateTime
	,@EndReportDate DateTime
	,@Paged BIT
)

AS
BEGIN

-- declare @Paged BIT
-- set @Paged = 1
-- declare @EndReportDate DateTime
-- set @EndReportDate = '1/1/2008'
-- declare @BegReportDate DateTime
-- set @BegReportDate = '1/1/1900'
-- declare @nRecordNumberStart INT
-- set @nRecordNumberStart = 1
-- declare @nRecordNumberEnd INT
-- set @nRecordNumberEnd = 100


IF @Paged = 1
	BEGIN
		DECLARE @totalRecords INT
		--------------------------------------------------------------------
		-- Define the table to do the filtering and paging
		--------------------------------------------------------------------
		DECLARE @tblTempData TABLE
		(
			nID INT IDENTITY
			,DayViews INT
			,DayComments INT
			,DayTrackbacks INT
			,DayPosts INT
			,DayArticles INT
			,ApplicationKey varchar(100)
		)
		INSERT INTO @tblTempData
		(
			DayViews
			,DayComments
			,DayTrackbacks
			,DayPosts
			,DayArticles
			,ApplicationKey
		)
		SELECT
			SUM(DayViews) AS DayViews, SUM(DayComments) AS DayComments, SUM(DayTrackBacks) AS DayTrackBacks
			,SUM(DayPosts) AS DayPosts, SUM(DayArticles) AS DayArticles
			,(SELECT  ApplicationKey FROM cs_Sections AS s WHERE  (SectionID = bar.SectionID)) AS ApplicationKey
		FROM
			cs_BlogActivityReport AS bar
			INNER JOIN cs_Sections sec ON sec.SectionID = bar.SectionID
		WHERE 
			ApplicationType = 1
		        AND bar.CoverageDate between @BegReportDate and @EndReportDate
			AND DayViews > 0
		GROUP BY
			bar.SectionID
		ORDER BY
			DayViews DESC
		SET @totalRecords = @@rowcount
		-------------------------------------------------------------------------------------
		
		SELECT
			DayViews
			,DayComments
			,DayTrackbacks
			,DayPosts
			,DayArticles
			,ApplicationKey
		FROM
			@tblTempData 
		WHERE
			nID BETWEEN @nRecordNumberStart AND @nRecordNumberEnd
		ORDER BY 
			nID ASC
		
		--Return Record Count
		SELECT @totalRecords

		--Return TotalBlogs
		SELECT COUNT(SectionID)
		FROM cs_Sections
		WHERE ApplicationType = 1

		--Return TotalEnabledBlogs
		SELECT COUNT(SectionID)
		FROM cs_Sections
		WHERE ApplicationType = 1 AND IsActive = 1

		--Return TotalDisabledBlogs
		SELECT COUNT(SectionID)
		FROM cs_Sections
		WHERE ApplicationType = 1 AND IsActive = 0
	END
ELSE
	BEGIN
		SELECT
			(SELECT  ApplicationKey FROM cs_Sections AS s WHERE  (SectionID = bar.SectionID)) AS ApplicationKey
			,SUM(DayViews) As TotalViews
			,SUM(DayComments) As TotalComments
			,SUM(DayTrackBacks) As TotalTrackBacks
			,SUM(DayPosts) As TotalPosts
			,SUM(DayArticles) As TotalArticles
		FROM
			cs_BlogActivityReport AS bar
			INNER JOIN cs_Sections sec ON sec.SectionID = bar.SectionID
		WHERE
			ApplicationType = 1
		        AND bar.CoverageDate between @BegReportDate and @EndReportDate
		GROUP BY
			bar.SectionID
		ORDER BY
			TotalViews DESC
	END
END                                                                                                                                                                                                                               


GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_BlogActivityReportAggregate_Get] to public
go

/***********************************************
* Sproc: cs_BlogActivityReportRecords_Get
* File Date: 11/29/2006 10:07:31 AM
***********************************************/
Print 'Creating...cs_BlogActivityReportRecords_Get'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_BlogActivityReportRecords_Get]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_BlogActivityReportRecords_Get]
GO

CREATE  PROCEDURE [dbo].cs_BlogActivityReportRecords_Get
(
	 @nRecordNumberStart INT
    	,@nRecordNumberEnd INT
        ,@BegReportDate DateTime
	,@EndReportDate DateTime
)

AS
BEGIN
	DECLARE @totalRecords INT

	--------------------------------------------------------------------
    	-- Define the table to do the filtering and paging
    	--------------------------------------------------------------------
    	DECLARE @tblTempData TABLE
        (
        	nID INT IDENTITY
        	,SectionID INT
        	,ThreadID INT
		,CoverageDate DateTime
        	,TotalViews INT
		,DayViews INT
		,DayComments INT
		,DayTrackbacks INT
		,IsPost bit
		,IsArticle bit
		,JobExecutionTimeStamp DateTime
		,PostID INT
		,PostSubject varchar(256)
		,ApplicationPostType INT
		,ApplicationKey varchar(100)
        )
	INSERT INTO @tblTempData
	(
        	SectionID
        	,ThreadID
		,CoverageDate
        	,TotalViews
		,DayViews
		,DayComments
		,DayTrackbacks
		,IsPost
		,IsArticle
		,JobExecutionTimeStamp
		,PostID
		,PostSubject
		,ApplicationPostType
		,ApplicationKey
        )
    	SELECT  SectionID, ThreadID, CoverageDate, TotalViews, DayViews, DayComments, DayTrackBacks, IsPost, IsArticle, JobExecutionTimeStamp,
    		(SELECT  PostID FROM     cs_Posts AS p WHERE  (PostLevel = 1) AND (ThreadID = bar.ThreadID)) AS PostID,
		(SELECT  Subject FROM     cs_Posts AS p WHERE  (PostLevel = 1) AND (ThreadID = bar.ThreadID)) AS PostSubject,
    		(SELECT  ApplicationPostType FROM     cs_Posts AS p WHERE  (PostLevel = 1) AND (ThreadID = bar.ThreadID)) AS ApplicationPostType,
    		(SELECT  ApplicationKey FROM     cs_Sections AS s WHERE  (SectionID = bar.SectionID)) AS ApplicationKey
	FROM     cs_BlogActivityReport AS bar
	WHERE 
		(((SELECT  ApplicationPostType FROM     cs_Posts AS p WHERE  (PostLevel = 1) AND (ThreadID = bar.ThreadID)) = 1)
                OR ((SELECT  ApplicationPostType FROM     cs_Posts AS p WHERE  (PostLevel = 1) AND (ThreadID = bar.ThreadID)) = 2))
                AND bar.CoverageDate between @BegReportDate and @EndReportDate
	ORDER BY
		bar.CoverageDate
	SET @totalRecords = @@rowcount
        ---------------------------------------------------------------------------------------------------------------------------------------
	SELECT
        	SectionID
        	,ThreadID
        	,TotalViews
		,DayViews
		,DayComments
		,DayTrackbacks
		,IsPost
		,IsArticle
		,JobExecutionTimeStamp
		,PostID
		,PostSubject
		,ApplicationPostType
		,ApplicationKey
		,CoverageDate
    	FROM
		@tblTempData 
    	WHERE
		nID BETWEEN @nRecordNumberStart AND @nRecordNumberEnd
    	ORDER BY 
        	nID ASC

-- Return totalRecords
SELECT @totalRecords

END
                                                                                                                                                                                                                                         


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].cs_BlogActivityReportRecords_Get to public
go

/***********************************************
* Sproc: cs_Censorships_Get
* File Date: 11/29/2006 10:07:31 AM
***********************************************/
Print 'Creating...cs_Censorships_Get'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Censorships_Get]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Censorships_Get]
GO


CREATE proc [dbo].cs_Censorships_Get
(
	@Word	nvarchar(40) = '',
	@SettingsID int
)
as
SET Transaction Isolation Level Read UNCOMMITTED
	select
		*
	from
		cs_Censorship
	WHERE
		SettingsID = @SettingsID and (Word = @Word or (@Word = '' AND 1=1))


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].cs_Censorships_Get to public
go

/***********************************************
* Sproc: cs_Censorship_CreateUpdateDelete
* File Date: 11/29/2006 10:07:32 AM
***********************************************/
Print 'Creating...cs_Censorship_CreateUpdateDelete'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Censorship_CreateUpdateDelete]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Censorship_CreateUpdateDelete]
GO


CREATE proc [dbo].cs_Censorship_CreateUpdateDelete
(
	  @Word			nvarchar(40)
	, @DeleteWord 	bit = 0
	, @Replacement	nvarchar(40)
	, @SettingsID int
)
as
SET Transaction Isolation Level Read UNCOMMITTED
SET NOCOUNT ON

if( @DeleteWord > 0 )
BEGIN
	DELETE FROM
		cs_Censorship
	WHERE
		Word = @Word and SettingsID = @SettingsID
	RETURN
END
ELSE
BEGIN
	UPDATE cs_Censorship SET
		Replacement	= @Replacement
	WHERE
		Word	= @Word and SettingsID = @SettingsID

	IF( @@rowcount = 0 )
	BEGIN
	INSERT INTO cs_Censorship (
		Word, Replacement, SettingsID
	) VALUES (
		@Word, @Replacement, @SettingsID
	)
	END
END


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT EXECUTE on [dbo].cs_Censorship_CreateUpdateDelete to public
GO
/***********************************************
* Sproc: cs_Content_CreateUpdateDelete
* File Date: 11/29/2006 10:07:31 AM
***********************************************/
Print 'Creating...cs_Content_CreateUpdateDelete'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Content_CreateUpdateDelete]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Content_CreateUpdateDelete]
GO

CREATE PROCEDURE [dbo].cs_Content_CreateUpdateDelete
(
	@ContentID	int out,
	@Action 	int,
	@Name		nvarchar(256),
	@Title		nvarchar(256),
	@Body		ntext,
	@FormattedBody	ntext,
	@Hidden		bit,
	@UpdateDate 	bit,
	@SettingsID 	int
)
AS
SET Transaction Isolation Level Read UNCOMMITTED
-- CREATE
IF @Action = 0
BEGIN
	-- first check that content name is not already in use
	IF EXISTS
	(
		SELECT  
			NULL
		FROM 
			cs_Content
		WHERE
			Name = @Name and SettingsID = @SettingsID
	)
	BEGIN
		RAISERROR ( 'Content name in use', 16, 1)
		RETURN
	END				

	DECLARE @SortOrder int

	SELECT @SortOrder = coalesce(MAX(SortOrder) + 1, 1) FROM cs_Content where SettingsID = @SettingsID

	-- Create a new content
	INSERT INTO 
		cs_Content 
		(
			Name,
			Title,
			Body,
			FormattedBody,
			Hidden,
			SortOrder,
			SettingsID
		)
	VALUES 
		(
			@Name,
			@Title,
			@Body,
			@FormattedBody,
			@Hidden,
			@SortOrder,
			@SettingsID
		)
	
	SET @ContentID = SCOPE_IDENTITY()
END


-- UPDATE
ELSE IF @Action = 1
BEGIN

	IF EXISTS
	(
		SELECT  
			NULL
		FROM 
			cs_Content c
		WHERE
			c.Name = @Name
			AND c.ContentID <> @ContentID and c.SettingsID = @SettingsID
	)
	BEGIN
		RAISERROR ( 'Content name in use', 16, 1)
		RETURN
	END				

	IF EXISTS(SELECT NULL FROM cs_Content WHERE ContentID = @ContentID)
	BEGIN
		UPDATE
			cs_Content
		SET
			Name = @Name,
			Title = @Title,
			Body = @Body,
			FormattedBody = @FormattedBody
		WHERE
			ContentID = @ContentID and SettingsID = @SettingsID

		IF @UpdateDate = 1 
			EXEC cs_Content_UpdateDate @ContentID
	END

END

-- DELETE
ELSE IF @Action = 2
BEGIN
	DELETE cs_Content WHERE ContentID = @ContentID and SettingsID = @SettingsID
END
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].cs_Content_CreateUpdateDelete to public
go
/***********************************************
* Sproc: cs_Content_GetIDFromName
* File Date: 11/29/2006 10:07:32 AM
***********************************************/
Print 'Creating...cs_Content_GetIDFromName'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Content_GetIDFromName]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Content_GetIDFromName]
GO
/***********************************************
* Sproc: cs_Content_GetList
* File Date: 11/29/2006 10:07:31 AM
***********************************************/
Print 'Creating...cs_Content_GetList'

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Content_GetList]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Content_GetList]
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

CREATE PROCEDURE [dbo].[cs_Content_GetList]
(
	@SettingsID int
)
AS
	SELECT  
		*
	FROM 
		cs_Content c
	WHERE 
		c.Hidden = 0 and c.SettingsID = @SettingsID
	ORDER BY 
		c.LastModified DESC
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_Content_GetList] to public
go

/***********************************************
* Sproc: cs_Content_Load
* File Date: 11/29/2006 10:07:30 AM
***********************************************/
Print 'Creating...cs_Content_Load'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Content_Load]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Content_Load]
GO

CREATE PROCEDURE [dbo].[cs_Content_Load]
(
	@ContentID int,
	@SettingsID int,
	@Name nvarchar(256) = null
)
AS
IF(@ContentID > 0)
BEGIN
	SELECT 
		[SettingsID], [ContentID], [Name], [Title], [Body], [FormattedBody], [LastModified], [SortOrder], [Hidden]
	FROM 
		[dbo].[cs_Content]
	WHERE
		ContentID = @ContentID and SettingsID = @SettingsID
END
ELSE
BEGIN
	SELECT 
		[SettingsID], [ContentID], [Name], [Title], [Body], [FormattedBody], [LastModified], [SortOrder], [Hidden]
	FROM 
		[dbo].[cs_Content]
	WHERE
		[Name] = @Name and SettingsID = @SettingsID

END
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].cs_Content_Load to public
go



/***********************************************
* Sproc: cs_Content_UpdateDate
* File Date: 11/29/2006 10:07:31 AM
***********************************************/
Print 'Creating...cs_Content_UpdateDate'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Content_UpdateDate]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Content_UpdateDate]
GO

CREATE PROCEDURE [dbo].[cs_Content_UpdateDate]
(
	@ContentID int
)
AS
	UPDATE
		cs_Content
	SET
		LastModified = getdate()
	WHERE
		ContentID = @ContentID
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].cs_Content_UpdateDate to public
go
/***********************************************
* Sproc: cs_DisallowedNames_Get
* File Date: 11/29/2006 10:07:31 AM
***********************************************/
Print 'Creating...cs_DisallowedNames_Get'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_DisallowedNames_Get]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_DisallowedNames_Get]
GO


CREATE PROCEDURE [dbo].cs_DisallowedNames_Get
(
	@SettingsID int
)
AS 
SET Transaction Isolation Level Read UNCOMMITTED

	SELECT 
		DisallowedName 
	FROM 
		cs_DisallowedNames
	WHERE
		SettingsID = @SettingsID 


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT EXECUTE on [dbo].cs_DisallowedNames_Get to public
go
/***********************************************
* Sproc: cs_DisallowedName_CreateUpdateDelete
* File Date: 11/29/2006 10:07:31 AM
***********************************************/
Print 'Creating...cs_DisallowedName_CreateUpdateDelete'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_DisallowedName_CreateUpdateDelete]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_DisallowedName_CreateUpdateDelete]
GO


CREATE PROCEDURE [dbo].cs_DisallowedName_CreateUpdateDelete
(
	@Name		nvarchar(64),
	@Replacement 	nvarchar(64),
	@DeleteName	bit = 0,
	@SettingsID int
)
AS
SET Transaction Isolation Level Read UNCOMMITTED
SET NOCOUNT ON

if( @DeleteName > 0 )
BEGIN
	DELETE FROM
		cs_DisallowedNames
	WHERE
		DisallowedName = @Name and SettingsID = @SettingsID
END
ELSE 
BEGIN
		UPDATE cs_DisallowedNames SET
			DisallowedName = @Replacement
		WHERE
			DisallowedName = @Name and SettingsID = @SettingsID

	if( @@rowcount = 0 )
	BEGIN
		INSERT INTO cs_DisallowedNames (
			DisallowedName, SettingsID
		) VALUES (
			@Name, @SettingsID
		)
		
	END
END


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT EXECUTE on [dbo].cs_DisallowedName_CreateUpdateDelete to public
go
/***********************************************
* Sproc: cs_EmailQueue_Delete
* File Date: 11/29/2006 10:07:29 AM
***********************************************/
Print 'Creating...cs_EmailQueue_Delete'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_EmailQueue_Delete]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_EmailQueue_Delete]
GO


create proc dbo.cs_EmailQueue_Delete
	@EmailID uniqueidentifier 
as
SET Transaction Isolation Level Read UNCOMMITTED
	delete from cs_EmailQueue where EmailID = @EmailID




GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT EXECUTE ON dbo.cs_EmailQueue_Delete TO public
GO
/***********************************************
* Sproc: cs_EmailQueue_Failure
* File Date: 11/29/2006 10:07:32 AM
***********************************************/
Print 'Creating...cs_EmailQueue_Failure'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_EmailQueue_Failure]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_EmailQueue_Failure]
GO


create proc dbo.cs_EmailQueue_Failure
	@EmailID uniqueidentifier,
	@FailureInterval int,
	@MaxNumberOfTries int
as
SET Transaction Isolation Level Read UNCOMMITTED
declare @NumberOfTries int
select @NumberOfTries = NumberOfTries + 1 from cs_EmailQueue where EmailID = @EmailID

if @NumberOfTries <= @MaxNumberOfTries
begin
	update cs_EmailQueue set
		NumberOfTries = @NumberOfTries,
		NextTryTime = dateadd(minute, @NumberOfTries * @FailureInterval, getdate())
	where EmailID = @EmailID
end
else
begin
	delete from cs_EmailQueue where EmailID = @EmailID
end
	
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT EXECUTE on dbo.cs_EmailQueue_Failure TO public
GO
/***********************************************
* Sproc: cs_Emails_Dequeue
* File Date: 11/29/2006 10:07:34 AM
***********************************************/
Print 'Creating...cs_Emails_Dequeue'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Emails_Dequeue]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Emails_Dequeue]
GO



CREATE    PROCEDURE [dbo].cs_Emails_Dequeue
(
	@SettingsID int
)
AS
SET Transaction Isolation Level Read UNCOMMITTED
BEGIN

	SELECT * FROM cs_EmailQueue Where SettingsID = @SettingsID and NextTryTime < getdate()
	
END




GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT EXECUTE ON [dbo].cs_Emails_Dequeue to public
go
/***********************************************
* Sproc: cs_Emails_Enqueue
* File Date: 11/29/2006 10:07:31 AM
***********************************************/
Print 'Creating...cs_Emails_Enqueue'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Emails_Enqueue]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Emails_Enqueue]
GO


CREATE  PROCEDURE [dbo].cs_Emails_Enqueue
(
	@EmailTo	nvarchar(2000),
	@EmailCc	ntext,
	@EmailBcc	ntext,
	@EmailFrom	nvarchar(256),
	@EmailSubject	nvarchar(1024),
	@EmailBody	ntext,
	@EmailPriority	int,
	@EmailBodyFormat int,
	@SettingsID int
)
AS
SET Transaction Isolation Level Read UNCOMMITTED
BEGIN

	INSERT INTO
		cs_EmailQueue
		(
			emailTo,
			emailCc,
			emailBcc,
			EmailFrom,
			EmailSubject,
			EmailBody,
			emailPriority,
			emailBodyFormat,
			SettingsID
		)
	VALUES
		(
			@EmailTo,
			@EmailCc,
			@EmailBcc,
			@EmailFrom,
			@EmailSubject,
			@EmailBody,
			@EmailPriority,
			@EmailBodyFormat,
			@SettingsID
		)		
END




GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT EXECUTE on [dbo].cs_Emails_Enqueue to public
go
/***********************************************
* Sproc: cs_Emails_TrackingSection
* File Date: 11/29/2006 10:07:31 AM
***********************************************/
Print 'Creating...cs_Emails_TrackingSection'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Emails_TrackingForum]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Emails_TrackingForum]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Emails_TrackingSection]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Emails_TrackingSection]
GO


CREATE PROCEDURE [dbo].cs_Emails_TrackingSection
(
	@PostID    INT,
	@SettingsID int
)
AS
SET Transaction Isolation Level Read UNCOMMITTED
DECLARE @SectionID INT
DECLARE @UserID INT
DECLARE @PostLevel INT
DECLARE @ThreadID INT

-- First get the post info
SELECT 
	@SectionID = SectionID, 
	@UserID = UserID,
	@PostLevel = PostLevel,
	@ThreadID = ThreadID
FROM 
	cs_Posts (nolock) 
WHERE 
	PostID = @PostID and SettingsID = @SettingsID

-- Check if its a new thread or not
IF (@PostLevel = 1)
BEGIN
	-- this is a new thread (1 & 2)
	
	-- Check if this is a PM message
	IF (@SectionID = 0)
	BEGIN
		
		-- we have to bind to the PM users for this ThreadID
		SELECT
			U.cs_UserID as UserID,
			U.Email,
			U.EnableHtmlEmail,
			F.SubscriptionType
		FROM
			cs_TrackedSections F
			JOIN cs_vw_Users_FullUser U (nolock) ON U.cs_UserID = F.UserID
			JOIN cs_PrivateMessages PM ON PM.UserID = F.UserID AND PM.ThreadID = @ThreadID
		WHERE
			F.SectionID IN (-1, 0) AND F.SettingsID = @SettingsID and U.SettingsID = @SettingsID and 
			U.EnableThreadTracking = 1 and
			F.SubscriptionType & 3 <> 0
	END
	ELSE BEGIN

		SELECT
			U.cs_UserID as UserID,
			U.Email, 
			U.EnableHtmlEmail,
			F.SubscriptionType
		FROM 
			cs_TrackedSections F
			JOIN cs_vw_Users_FullUser U (nolock) ON U.cs_UserID = F.UserID
		WHERE
			F.SectionID = @SectionID AND F.SettingsID = @SettingsID and U.SettingsID = @SettingsID and
			U.EnableThreadTracking = 1 and
			F.SubscriptionType & 3 <> 0
	END
END
ELSE BEGIN
	-- this is a reply to an existing post (2)

	-- Check if this is a PM message
	IF (@SectionID = 0)
	BEGIN
		
		-- we have to bind to the PM users for this ThreadID
		SELECT
			U.cs_UserID as UserID,
			U.Email,
			U.EnableHtmlEmail,
			F.SubscriptionType
		FROM
			cs_TrackedSections F
			JOIN cs_vw_Users_FullUser U (nolock) ON U.cs_UserID = F.UserID
			JOIN cs_PrivateMessages PM ON PM.UserID = F.UserID AND PM.ThreadID = @ThreadID
		WHERE
			F.SectionID IN (-1, 0) AND U.SettingsID = @SettingsID and F.SettingsID = @SettingsID and
			F.SubscriptionType & 3 = 3

	END
	ELSE BEGIN

		SELECT
			U.cs_UserID as UserID,
			U.Email, 
			U.EnableHtmlEmail,
			F.SubscriptionType
		FROM 
			cs_TrackedSections F
			JOIN cs_vw_Users_FullUser U (nolock) ON U.cs_UserID = F.UserID			
		WHERE
			F.SectionID = @SectionID AND U.SettingsID = @SettingsID and F.SettingsID = @SettingsID and 
			F.SubscriptionType & 3 = 3
	END
END
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].cs_Emails_TrackingSection to public
go
/***********************************************
* Sproc: cs_Emails_TrackingThread
* File Date: 11/29/2006 10:07:30 AM
***********************************************/
Print 'Creating...cs_Emails_TrackingThread'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Emails_TrackingThread]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Emails_TrackingThread]
GO



CREATE PROCEDURE [dbo].cs_Emails_TrackingThread
(
	@PostID INT,
	@SettingsID int
)
AS
SET Transaction Isolation Level Read UNCOMMITTED
DECLARE @SectionID INT
DECLARE @UserID INT
DECLARE @PostLevel INT
DECLARE @ThreadID INT

-- First get the post info
SELECT 
	@SectionID = SectionID, 
	@UserID = UserID,
	@PostLevel = PostLevel,
	@ThreadID = ThreadID
FROM 
	cs_Posts (nolock) 
WHERE 
	PostID = @PostID and SettingsID = @SettingsID


-- Check if this is a PM message
IF (@SectionID = 0)
BEGIN
	
	-- we have to bind to the PM users for this ThreadID
	SELECT
		U.cs_UserID as UserID,
		U.Email,
		U.EnableHtmlEmail
	FROM
		cs_TrackedThreads T
		JOIN cs_vw_Users_FullUser U (nolock) ON U.cs_UserID = T.UserID
				JOIN cs_PrivateMessages PM ON PM.UserID = T.UserID AND PM.ThreadID = @ThreadID
	WHERE
		T.ThreadID = @ThreadID and T.SettingsID = @SettingsID and U.SettingsID = @SettingsID and PM.SettingsID = @SettingsID and
		U.EnableThreadTracking = 1

END
ELSE BEGIN

	SELECT
		U.cs_UserID as UserID,
		U.Email, 
		U.EnableHtmlEmail
	FROM 
		cs_TrackedThreads T
		JOIN cs_vw_Users_FullUser U (nolock) ON U.cs_UserID = T.UserID			
	WHERE
		T.ThreadID = @ThreadID and T.SettingsID = @SettingsID and U.SettingsID = @SettingsID and
		U.EnableThreadTracking = 1
END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].cs_Emails_TrackingThread to public
go
/***********************************************
* Sproc: cs_es_sprocs
* File Date: 11/29/2006 10:07:31 AM
***********************************************/
Print 'Creating...cs_es_sprocs'


SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_es_Search_QueueManager]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_es_Search_QueueManager]
GO


Create Proc [dbo].cs_es_Search_QueueManager
(
	@PostID int,
	@SettingsID int,
	@Add bit
)

as

if @Add = 1
Begin

	Insert cs_es_Search_RemoveQueue (PostID, SettingsID) Values (@PostID, @SettingsID)

End
ELSE
BEGIN
	DELETE FROM cs_es_Search_RemoveQueue where PostID = @PostID and SettingsID = @SettingsID
END


SET QUOTED_IDENTIFIER OFF 




GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].cs_es_Search_QueueManager to public
go



SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_es_Search_Queue_Get]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_es_Search_Queue_Get]
GO


Create Proc [dbo].cs_es_Search_Queue_Get
(
	@SettingsID int
)

as

Select PostID FROM cs_es_Search_RemoveQueue where SettingsID = @SettingsID



SET QUOTED_IDENTIFIER OFF 




GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].cs_es_Search_Queue_Get to public
go
/***********************************************
* Sproc: cs_EventLog_Add
* File Date: 11/29/2006 10:07:32 AM
***********************************************/
Print 'Creating...cs_EventLog_Add'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_EventLog_Add]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_EventLog_Add]
GO

CREATE PROCEDURE [dbo].cs_EventLog_Add
(
	@EventType int,
	@Message ntext,
	@Category nvarchar(256),
	@MachineName nvarchar(256) = null,
	@EventID int,
	@SettingsID int
) AS

INSERT INTO [cs_EventLog]([Message], [Category], [SettingsID], [EventID], [EventType], [MachineName])
VALUES(  @Message, @Category, @SettingsID, @EventID, @EventType, @MachineName)


SET QUOTED_IDENTIFIER OFF 




GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].cs_EventLog_Add to public
go
/***********************************************
* Sproc: cs_EventLog_Clear
* File Date: 11/29/2006 10:07:30 AM
***********************************************/
Print 'Creating...cs_EventLog_Clear'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_EventLog_Clear]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_EventLog_Clear]
GO

CREATE PROCEDURE [dbo].cs_EventLog_Clear
(
	@Date datetime
) AS

Delete FROM cs_EventLog where  EventDate <= @Date

SET QUOTED_IDENTIFIER OFF 




GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].cs_EventLog_Clear to public
go
/***********************************************
* Sproc: cs_EventLog_GetEntries
* File Date: 11/29/2006 10:07:33 AM
***********************************************/
Print 'Creating...cs_EventLog_GetEntries'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_EventLog_GetEntries]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_EventLog_GetEntries]
GO

CREATE PROCEDURE [dbo].cs_EventLog_GetEntries
(
	@SettingsID int = -1
)
AS
	SELECT TOP 1000
				EL.EventLogID,
				EL.Message,
				EL.Category,
				EL.SettingsID,
				EL.EventID,
				EL.EventType,
				EL.EventDate,
				EL.MachineName
	FROM		cs_EventLog EL
	WHERE		EL.SettingsID = @SettingsID
		OR		EL.SettingsID = -1
	ORDER BY	EL.EventLogID DESC
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].cs_EventLog_GetEntries to public
go
/***********************************************
* Sproc: cs_EventLog_GetEntry
* File Date: 11/29/2006 10:07:33 AM
***********************************************/
Print 'Creating...cs_EventLog_GetEntry'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_EventLog_GetEntry]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_EventLog_GetEntry]
GO

CREATE PROCEDURE [dbo].cs_EventLog_GetEntry
(
	@EntryID int
)
AS
	SELECT		EL.EventLogID,
				EL.Message,
				EL.Category,
				EL.SettingsID,
				EL.EventID,
				EL.EventType,
				EL.EventDate,
				EL.MachineName
	FROM		cs_EventLog EL
	WHERE		EL.EventLogID = @EntryID
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].cs_EventLog_GetEntry to public
go
/***********************************************
* Sproc: cs_Exceptions_Get
* File Date: 11/29/2006 10:07:30 AM
***********************************************/
Print 'Creating...cs_Exceptions_Get'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Exceptions_Get]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Exceptions_Get]
GO




CREATE  procedure [dbo].cs_Exceptions_Get
(
	@SettingsID int,
	@ExceptionType int = 0,
	@MinFrequency int = 10,
	@SortOrder int = 1,
	@IncludeUnknown bit = 0
)
AS
SET Transaction Isolation Level Read UNCOMMITTED
BEGIN

IF @SortOrder = 1
	SELECT TOP 100
		E.*
	FROM
		cs_Exceptions E
	WHERE
		E.SettingsID = @SettingsID AND
		((@ExceptionType > 0 and E.Category = @ExceptionType ) or @ExceptionType <= 0 ) AND
		E.Frequency >= @MinFrequency
		AND (@IncludeUnknown = 1 OR (@IncludeUnknown = 0 AND E.Category <> 999))
	ORDER BY
		E.DateLastOccurred DESC, E.Frequency DESC
ELSE
	SELECT TOP 100
		E.*
	FROM
		cs_Exceptions E
	WHERE
		E.SettingsID = @SettingsID AND
		((@ExceptionType > 0 and E.Category = @ExceptionType ) or @ExceptionType <= 0 ) AND
		E.Frequency >= @MinFrequency
		AND (@IncludeUnknown = 1 OR (@IncludeUnknown = 0 AND E.Category <> 999))
	ORDER BY
		E.Frequency DESC, E.DateLastOccurred DESC
END



GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].cs_Exceptions_Get to public
go
/***********************************************
* Sproc: cs_Exceptions_Log
* File Date: 11/29/2006 10:07:33 AM
***********************************************/
Print 'Creating...cs_Exceptions_Log'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Exceptions_Log]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Exceptions_Log]
GO




CREATE procedure [dbo].cs_Exceptions_Log
(
	@SettingsID int,
	@ExceptionHash varchar(128),
	@Category int,
	@Exception nvarchar(2000),
	@ExceptionMessage nvarchar(500),
	@UserAgent nvarchar(64),
	@IPAddress varchar(15),
	@HttpReferrer nvarchar (256),
	@HttpVerb nvarchar(24),
	@PathAndQuery nvarchar(512)
)
AS
BEGIN

SET Transaction Isolation Level Read UNCOMMITTED

IF EXISTS (SELECT ExceptionID FROM cs_Exceptions WHERE ExceptionHash = @ExceptionHash and SettingsID = @SettingsID)

	UPDATE
		cs_Exceptions
	SET
		DateLastOccurred = GetDate(),
		Frequency = Frequency + 1
	WHERE
		ExceptionHash = @ExceptionHash and SettingsID = @SettingsID
ELSE
	INSERT INTO 
		cs_Exceptions
	(
		ExceptionHash,
		SettingsID,
		Category,
		Exception,
		ExceptionMessage,
		UserAgent,
		IPAddress,
		HttpReferrer,
		HttpVerb,
		PathAndQuery,
		DateCreated,
		DateLastOccurred,
		Frequency
	)
	VALUES
	(
		@ExceptionHash,
		@SettingsID,
		@Category,
		@Exception,
		@ExceptionMessage,
		@UserAgent,
		@IPAddress,
		@HttpReferrer,
		@HttpVerb,
		@PathAndQuery,
		GetDate(),
		GetDate(),
		1
	)

END











GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].cs_Exceptions_Log to public
go
/***********************************************
* Sproc: cs_Favorites_Get
* File Date: 11/29/2006 10:07:34 AM
***********************************************/
Print 'Creating...cs_Favorites_Get'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Favorites_Get]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Favorites_Get]
GO

CREATE procedure dbo.cs_Favorites_Get
(
	@FavoriteType	int,
	@UserID			int,
	@SettingsID		int
)
AS
	SET Transaction Isolation Level Read UNCOMMITTED

	IF @FavoriteType = 1		-- Section

		SELECT
			F.FavoriteID,
			F.OwnerID AS UserID,
			F.SettingsID,
			F.SectionID AS ItemID,
			@FavoriteType AS FavoriteType,
			F.ApplicationType
		FROM
			cs_FavoriteSections F
		WHERE
			F.OwnerID = @UserID AND
			F.SettingsID = @SettingsID

	ELSE IF @FavoriteType = 2	-- User

		SELECT
			F.FavoriteID,
			F.OwnerID AS UserID,
			F.SettingsID,
			F.UserID AS ItemID,
			@FavoriteType AS FavoriteType,
			F.ApplicationType
		FROM
			cs_FavoriteUsers F
		WHERE
			F.OwnerID = @UserID AND
			F.SettingsID = @SettingsID

	ELSE IF @FavoriteType = 4	-- Post

		SELECT
			F.FavoriteID,
			F.OwnerID AS UserID,
			F.SettingsID,
			F.PostID AS ItemID,
			@FavoriteType AS FavoriteType,
			F.ApplicationType
		FROM
			cs_FavoritePosts F
		WHERE
			F.OwnerID = @UserID AND
			F.SettingsID = @SettingsID

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT EXECUTE on [dbo].[cs_Favorites_Get] to public

/***********************************************
* Sproc: cs_Favorites_GetPosts
* File Date: 11/29/2006 10:07:33 AM
***********************************************/
Print 'Creating...cs_Favorites_GetPosts'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Favorites_GetPosts]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Favorites_GetPosts]
GO

CREATE procedure dbo.cs_Favorites_GetPosts
(
	@UserID		int,
	@SettingsID	int
)
AS
	SET Transaction Isolation Level Read UNCOMMITTED

SELECT
	FP.ApplicationType,
	U.*,
	jP.TotalRatings AS PostTotalRatings,
	jP.RatingSum AS PostRatingSum,
	jP.PostID, 
	jP.ThreadID, 
	jP.ParentID, 
	jP.PostAuthor, 
	jP.UserID, 
	jP.SectionID, 
	jP.PostLevel, 
	jP.SortOrder, 
	jP.Subject, 
	jP.PostDate, 
	jP.IsApproved,
	jP.IsLocked as IsLocked,
	jP.IsIndexed, 
	jP.TotalViews as PostTotalViews,  --Conflicts with the Threads table which has precidence
	jP.Body, 
	jP.FormattedBody, 
	jP.IPAddress, 
	jP.PostType, 
	jP.PostMedia, 
	jP.EmoticonID, 
	jP.SettingsID, 
	jP.AggViews,
	jP.PostPropertyNames, 
	jP.PostPropertyValues,
	jP.PostConfiguration,
	jP.Points AS PostPoints,
	jP.PostStatus,
	jP.SpamScore,
	
	jp.AttachmentFilename,jp.ContentType, jp.IsRemote, jp.FriendlyFileName, jp.ContentSize, jp.[FileName],jp.Created, jP.Height, jP.Width,
	jP.PostName, 
	jP.ApplicationPostType, 
	jP.UserTime, 
	HasRead = 1,
	EditNotes = null, --(SELECT EditNotes FROM cs_PostEditNotes WHERE PostID = P.PostID),

	jT.PostAuthor as UserName,
	jT.TotalReplies as Replies, -- (SELECT COUNT(P2.PostID) FROM cs_Posts P2 (nolock) WHERE P2.ParentID = jP.PostID AND P2.PostLevel != 1)

        jT.UserID as ThreadUserID,
        jT.PostAuthor as ThreadPostAuthor,
        jT.PostDate as ThreadPostDate,
        jT.ThreadDate,
        jT.LastViewedDate,
        jT.StickyDate,
        jT.TotalViews as TotalViews,
        jT.TotalReplies,
        jT.MostRecentPostAuthorID,
        jT.MostRecentPostAuthor,
        jT.MostRecentPostID,
        jT.IsLocked as ThreadIsLocked,
        jT.IsSticky,
        jT.IsApproved as ThreadIsApproved,
        jT.RatingSum,
        jT.TotalRatings,
        jT.ThreadEmoticonID,
        jT.ThreadStatus,
        jT.SettingsID
FROM
	cs_FavoritePosts FP
	JOIN cs_vw_PostsWithAttachmentDetails jP ON FP.PostID = jP.PostID
	JOIN cs_vw_Users_FullUser U ON jP.userID = U.cs_UserID
	JOIN cs_Threads jT ON jP.ThreadID = jT.ThreadID
WHERE
	FP.OwnerID = @UserID
	AND jp.SettingsID = @SettingsID AND jT.SettingsID = @SettingsID AND U.SettingsID = @SettingsID
ORDER BY
	jP.Subject

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT EXECUTE on [dbo].[cs_Favorites_GetPosts] to public

/***********************************************
* Sproc: cs_Favorites_GetSections
* File Date: 11/29/2006 10:07:31 AM
***********************************************/
Print 'Creating...cs_Favorites_GetSections'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Favorites_GetSections]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Favorites_GetSections]
GO

CREATE procedure dbo.cs_Favorites_GetSections
(
	@UserID		int,
	@SettingsID	int
)
AS
	SET Transaction Isolation Level Read UNCOMMITTED

	SELECT
		F.SectionID,
		F.ApplicationType
	FROM
		cs_FavoriteSections F
	WHERE
		F.OwnerID = @UserID AND
		F.SettingsID = @SettingsID

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT EXECUTE on [dbo].[cs_Favorites_GetSections] to public

/***********************************************
* Sproc: cs_Favorites_GetUsers
* File Date: 11/29/2006 10:07:31 AM
***********************************************/
Print 'Creating...cs_Favorites_GetUsers'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Favorites_GetUsers]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Favorites_GetUsers]
GO

CREATE procedure dbo.cs_Favorites_GetUsers
(
	@UserID		int,
	@SettingsID	int
)
AS
	SET Transaction Isolation Level Read UNCOMMITTED

	SELECT
		U.*
	FROM
		cs_FavoriteUsers F,
		cs_vw_Users_FullUser U
	WHERE
		F.UserID = U.cs_UserID AND
		F.OwnerID = @UserID AND
		F.SettingsID = @SettingsID AND
		U.SettingsID = @SettingsID

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT EXECUTE on [dbo].[cs_Favorites_GetUsers] to public

/***********************************************
* Sproc: cs_Favorites_GetUsersWatching
* File Date: 11/29/2006 10:07:31 AM
***********************************************/
Print 'Creating...cs_Favorites_GetUsersWatching'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Favorites_GetUsersWatching]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Favorites_GetUsersWatching]
GO

CREATE procedure dbo.cs_Favorites_GetUsersWatching
(
	@UserID		int,
	@SettingsID	int
)
AS
	SET Transaction Isolation Level Read UNCOMMITTED

	SELECT
		U.*
	FROM
		cs_FavoriteUsers F,
		cs_vw_Users_FullUser U
	WHERE
		F.OwnerID = U.cs_UserID AND
		F.UserID = @UserID AND
		F.SettingsID = @SettingsID AND
		U.SettingsID = @SettingsID AND
		(U.FavoritesShared & 2) = 2		-- sharing users

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT EXECUTE on [dbo].[cs_Favorites_GetUsersWatching] to public

/***********************************************
* Sproc: cs_Favorite_Add
* File Date: 11/29/2006 10:07:31 AM
***********************************************/
Print 'Creating...cs_Favorite_Add'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Favorite_Add]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Favorite_Add]
GO

CREATE PROCEDURE dbo.cs_Favorite_Add
(
	@SettingsID			int,
	@UserID				int,
	@ItemID				int,
	@FavoriteType		int,
	@ApplicationType	int,
	@FavoriteID			int OUTPUT
)
AS
	SET NOCOUNT ON
	SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED


	IF @FavoriteType = 1		-- Section
	BEGIN

		-- Check if favorite already exists, return existing id
		SELECT	@FavoriteID = F.FavoriteID
		FROM	cs_FavoriteSections F
		WHERE	OwnerID = @UserID
			AND	SettingsID = @SettingsID
			AND	SectionID = @ItemID
			AND	ApplicationType = @ApplicationType

		-- New favorite
		IF @FavoriteID IS NULL
		BEGIN

			INSERT INTO cs_FavoriteSections
				(OwnerID, SettingsID, SectionID, ApplicationType)
			VALUES
				(@UserID, @SettingsID, @ItemID, @ApplicationType)

			SET @FavoriteID = SCOPE_IDENTITY()
		END
	END

	ELSE IF @FavoriteType = 2	-- User
	BEGIN

		-- Check if favorite already exists, return existing id
		SELECT	@FavoriteID = F.FavoriteID
		FROM	cs_FavoriteUsers F
		WHERE	OwnerID = @UserID
			AND	SettingsID = @SettingsID
			AND	UserID = @ItemID
			AND	ApplicationType = @ApplicationType

		-- New favorite
		IF @FavoriteID IS NULL
		BEGIN

			INSERT INTO cs_FavoriteUsers
				(OwnerID, SettingsID, UserID, ApplicationType)
			VALUES
				(@UserID, @SettingsID, @ItemID, @ApplicationType)

			SET @FavoriteID = SCOPE_IDENTITY()
		END
	END

	ELSE IF @FavoriteType = 4	-- Post
	BEGIN

		-- Check if favorite already exists, return existing id
		SELECT	@FavoriteID = F.FavoriteID
		FROM	cs_FavoritePosts F
		WHERE	OwnerID = @UserID
			AND	SettingsID = @SettingsID
			AND	PostID = @ItemID
			AND	ApplicationType = @ApplicationType

		-- New favorite
		IF @FavoriteID IS NULL
		BEGIN

			INSERT INTO cs_FavoritePosts
				(OwnerID, SettingsID, PostID, ApplicationType)
			VALUES
				(@UserID, @SettingsID, @ItemID, @ApplicationType)

			SET @FavoriteID = SCOPE_IDENTITY()
		END
	END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT EXECUTE on [dbo].[cs_Favorite_Add] to public

/***********************************************
* Sproc: cs_Favorite_Delete
* File Date: 11/29/2006 10:07:31 AM
***********************************************/
Print 'Creating...cs_Favorite_Delete'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Favorite_Delete]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Favorite_Delete]
GO

CREATE PROCEDURE dbo.cs_Favorite_Delete
(
	@FavoriteType	int,
	@FavoriteID		int
)
AS
	IF @FavoriteType = 1		-- Section

		DELETE
		FROM	cs_FavoriteSections
		WHERE	FavoriteID = @FavoriteID

	ELSE IF @FavoriteType = 2	-- User

		DELETE
		FROM	cs_FavoriteUsers
		WHERE	FavoriteID = @FavoriteID

	ELSE IF @FavoriteType = 4	-- Post

		DELETE
		FROM	cs_FavoritePosts
		WHERE	FavoriteID = @FavoriteID

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT EXECUTE on [dbo].[cs_Favorite_Delete] to public

/***********************************************
* Sproc: cs_Favorite_Get
* File Date: 11/29/2006 10:07:34 AM
***********************************************/
Print 'Creating...cs_Favorite_Get'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Favorite_Get]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Favorite_Get]
GO

CREATE procedure dbo.cs_Favorite_Get
(
	@FavoriteType	int,
	@FavoriteID		int
)
AS
	SET NOCOUNT ON
	SET Transaction Isolation Level Read UNCOMMITTED


	IF @FavoriteType = 1		-- Section

		SELECT
			F.FavoriteID,
			F.OwnerID AS UserID,
			F.SettingsID,
			F.SectionID AS ItemID,
			@FavoriteType AS FavoriteType,
			F.ApplicationType
		FROM
			cs_FavoriteSections F
		WHERE
			F.FavoriteID = @FavoriteID

	ELSE IF @FavoriteType = 2	-- User

		SELECT
			F.FavoriteID,
			F.OwnerID AS UserID,
			F.SettingsID,
			F.UserID AS ItemID,
			@FavoriteType AS FavoriteType,
			F.ApplicationType
		FROM
			cs_FavoriteUsers F
		WHERE
			F.FavoriteID = @FavoriteID

	ELSE IF @FavoriteType = 4	-- Post

		SELECT
			F.FavoriteID,
			F.OwnerID AS UserID,
			F.SettingsID,
			F.PostID AS ItemID,
			@FavoriteType AS FavoriteType,
			F.ApplicationType
		FROM
			cs_FavoritePosts F
		WHERE
			F.FavoriteID = @FavoriteID

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT EXECUTE on [dbo].[cs_Favorite_Get] to public

/***********************************************
* Sproc: cs_Favorite_GetByUserItem
* File Date: 11/29/2006 10:07:30 AM
***********************************************/
Print 'Creating...cs_Favorite_GetByUserItem'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Favorite_GetByUserItem]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Favorite_GetByUserItem]
GO

CREATE procedure dbo.cs_Favorite_GetByUserItem
(
	@SettingsID		int,
	@FavoriteType	int,
	@UserID			int,
	@ItemID			int
)
AS
	SET NOCOUNT ON
	SET Transaction Isolation Level Read UNCOMMITTED


	IF @FavoriteType = 1		-- Section

		SELECT
			F.FavoriteID,
			F.OwnerID AS UserID,
			F.SettingsID,
			F.SectionID AS ItemID,
			@FavoriteType AS FavoriteType,
			F.ApplicationType
		FROM
			cs_FavoriteSections F
		WHERE
			F.OwnerID = @UserID AND
			F.SectionID = @ItemID AND
			F.SettingsID = @SettingsID

	ELSE IF @FavoriteType = 2	-- User

		SELECT
			F.FavoriteID,
			F.OwnerID AS UserID,
			F.SettingsID,
			F.UserID AS ItemID,
			@FavoriteType AS FavoriteType,
			F.ApplicationType
		FROM
			cs_FavoriteUsers F
		WHERE
			F.OwnerID = @UserID AND
			F.UserID = @ItemID AND
			F.SettingsID = @SettingsID

	ELSE IF @FavoriteType = 4	-- Post

		SELECT
			F.FavoriteID,
			F.OwnerID AS UserID,
			F.SettingsID,
			F.PostID AS ItemID,
			@FavoriteType AS FavoriteType,
			F.ApplicationType
		FROM
			cs_FavoritePosts F
		WHERE
			F.OwnerID = @UserID AND
			F.PostID = @ItemID AND
			F.SettingsID = @SettingsID

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT EXECUTE on [dbo].[cs_Favorite_GetByUserItem] to public

/***********************************************
* Sproc: cs_FeedPost_GetPost
* File Date: 11/29/2006 10:07:31 AM
***********************************************/
Print 'Creating...cs_FeedPost_GetPost'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_FeedPost_GetPost]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_FeedPost_GetPost]
GO


CREATE PROC [dbo].cs_FeedPost_GetPost
	@FeedPostId INT
AS


SELECT 	FeedPostId,
	FeedId,
	Author,
	Title,
	Description,
	Source,
	GuidName,
	GuidIsPermaLink,
	Link,
	PubDate,
	CommentsUrl,
	EnclosureUrl,
	EnclosureLength,
	EnclosureType,
	Creator,
	CommentApiUrl,
	CommentRssUrl,
	CommentCount
FROM cs_FeedPost
WHERE FeedPostId = @FeedPostId


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT EXECUTE ON [dbo].cs_FeedPost_GetPost  TO PUBLIC
GO

/***********************************************
* Sproc: cs_FeedPost_GetPostFullDetails
* File Date: 11/29/2006 10:07:33 AM
***********************************************/
Print 'Creating...cs_FeedPost_GetPostFullDetails'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_FeedPost_GetPostFullDetails]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_FeedPost_GetPostFullDetails]
GO


CREATE PROC [dbo].cs_FeedPost_GetPostFullDetails
	@FeedId INT
AS


SELECT 	fp.FeedPostId,
	fp.FeedId,
	fp.Author,
	fp.Title,
	fp.Description,
	fp.Source,
	fp.GuidName,
	fp.GuidIsPermaLink,
	fp.Link,
	fp.PubDate,
	fp.CommentsUrl,
	fp.EnclosureUrl,
	fp.EnclosureLength,
	fp.EnclosureType,
	fp.Creator,
	fp.CommentApiUrl,
	fp.CommentRssUrl,
	fp.CommentCount
FROM 	cs_FeedPost fp,
	cs_Feed f
WHERE f.FeedId = fp.FeedId
  AND fp.FeedPostId = @FeedId


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT EXECUTE ON [dbo].cs_FeedPost_GetPostFullDetails  TO PUBLIC
GO

/***********************************************
* Sproc: cs_FeedPost_UpdatePosts
* File Date: 11/29/2006 10:07:31 AM
***********************************************/
Print 'Creating...cs_FeedPost_UpdatePosts'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_FeedPost_UpdatePosts]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_FeedPost_UpdatePosts]
GO



CREATE PROC [dbo].cs_FeedPost_UpdatePosts
	@FeedId INT,
	@FeedItemList NTEXT
AS

SET NOCOUNT ON

DECLARE @idoc INT
DECLARE @FeedPosts TABLE
(
	FeedId INT,
	Author NVARCHAR(255),
	Title NVARCHAR(255),
	Description NTEXT,
	Source NVARCHAR(255),
	GuidName NVARCHAR(255) collate database_default,
	GuidIsPermaLink BIT,
	Link NVARCHAR(255),
	PubDate DATETIME,
	CommentsUrl NVARCHAR(255),
	EnclosureUrl VARCHAR(255),
	EnclosureLength BIGINT,
	EnclosureType NVARCHAR(100),
	Creator NVARCHAR(255) NULL,
	CommentApiUrl NVARCHAR(255) NULL,
	CommentRssUrl NVARCHAR(255) NULL,
	CommentCount INT NULL
)

EXEC sp_xml_preparedocument @idoc OUTPUT, @FeedItemList

-- First off, let's move all the XML into the table variable.
INSERT INTO @FeedPosts
  SELECT C.FeedId,
	C.Author,
	C.Title,
	C.Description,
	C.Source,
	C.GuidName,
	C.GuidIsPermaLink,
	C.Link,
	C.PubDate,
	C.CommentsUrl,
	C.EnclosureUrl,
	C.EnclosureLength,
	C.EnclosureType,
	C.Creator,
	C.CommentApiUrl,
	C.CommentRssUrl,
	C.CommentCount
FROM OPENXML(@idoc, '/feeds/feed', 3)  
WITH (	FeedId INT,
	Author NVARCHAR(255),
	Title NVARCHAR(255),
	Description NTEXT,
	Source NVARCHAR(255),
	GuidName NVARCHAR(255),
	GuidIsPermaLink BIT,
	Link NVARCHAR(255),
	PubDate DATETIME,
	CommentsUrl NVARCHAR(255),
	EnclosureUrl VARCHAR(255),
	EnclosureLength BIGINT,
	EnclosureType NVARCHAR(100),
	Creator NVARCHAR(255),
	CommentApiUrl NVARCHAR(255),
	CommentRssUrl NVARCHAR(255),
	CommentCount INT) AS C

-- Insert missing posts
INSERT INTO cs_FeedPost
(
	FeedId,
	Author,
	Title,
	Description,
	Source,
	GuidName,
	GuidIsPermaLink,
	Link,
	PubDate,
	CommentsUrl,
	EnclosureUrl,
	EnclosureLength,
	EnclosureType,
	Creator,
	CommentApiUrl,
	CommentRssUrl,
	CommentCount
	
)
SELECT 	C.FeedId,
	C.Author,
	C.Title,
	C.Description,
	C.Source,
	C.GuidName,
	C.GuidIsPermaLink,
	C.Link,
	C.PubDate,
	C.CommentsUrl,
	C.EnclosureUrl,
	C.EnclosureLength,
	C.EnclosureType,
	C.Creator,
	C.CommentApiUrl,
	C.CommentRssUrl,
	C.CommentCount
FROM @FeedPosts AS C
WHERE C.GuidName NOT IN 	(
  SELECT GuidName FROM cs_FeedPost 
  WHERE FeedId = @FeedId
			)  

-- Update existing posts.
UPDATE cs_FeedPost
SET	Author = C.Author,
	Title = C.Title,
	Description = C.Description,
	Source = C.Source,
	GuidName = C.GuidName,
	GuidIsPermaLink = C.GuidIsPermaLink,
	Link = C.Link,
	PubDate = C.PubDate,
	CommentsUrl = C.CommentsUrl,
	EnclosureUrl = C.EnclosureUrl,
	EnclosureLength = C.EnclosureLength,
	EnclosureType = C.EnclosureType,
	Creator = C.Creator,
	CommentApiUrl = C.CommentApiUrl,
	CommentRssUrl = C.CommentRssUrl,
	CommentCount = C.CommentCount
FROM @FeedPosts AS C
WHERE cs_FeedPost.GuidName = C.GuidName



EXEC sp_xml_removedocument @idoc



GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT EXECUTE ON [dbo].cs_FeedPost_UpdatePosts  TO PUBLIC
GO

/***********************************************
* Sproc: cs_Feed_AddFeed
* File Date: 11/29/2006 10:07:30 AM
***********************************************/
Print 'Creating...cs_Feed_AddFeed'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Feed_AddFeed]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Feed_AddFeed]
GO


CREATE PROC [dbo].cs_Feed_AddFeed
	@FolderId INT = NULL,
	@UserId INT,
	@Url NVARCHAR(255),
	@SettingsID INT,
	@FeedId INT OUTPUT
AS


DECLARE @NewFeedId INT


-- First, let's see if the feed is already registered.
SELECT @NewFeedId = FeedId
FROM cs_Feed
WHERE Url = @Url and SettingsID = @SettingsID


-- If it's not, let's insert it and grab the FeedId.
IF (@NewFeedId IS NULL)
  BEGIN
	
	-- Insert it.
	INSERT INTO cs_Feed
	(
		Url,
		SettingsID
	) 
	VALUES
	(
		@Url,
		@SettingsID
	)

	-- Grab the identity generated.
	SELECT @NewFeedId = @@IDENTITY

  END

-- Add the feed to the user's folder.
INSERT INTO cs_FolderFeed
(
	UserId,
	FolderId,
	FeedId,
	SettingsID
)
VALUES
(
	@UserId,
	@FolderId,
	@NewFeedId,
	@SettingsID
)

SELECT @FeedId = @NewFeedId


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT EXECUTE ON [dbo].cs_Feed_AddFeed  TO PUBLIC
GO

/***********************************************
* Sproc: cs_Feed_GetAll
* File Date: 11/29/2006 10:07:33 AM
***********************************************/
Print 'Creating...cs_Feed_GetAll'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Feed_GetAll]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Feed_GetAll]
GO


CREATE PROC [dbo].cs_Feed_GetAll
(
	@SettingsID int
)
AS

SELECT  FeedId,
	Url,
	Title,
	Link,
	Language,
	Generator,
	SubscribeDate,
	LastUpdateDate,
	FeedStateId,
	LastModified,
	ETag
FROM cs_Feed
WHERE SettingsID = @SettingsID

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT EXECUTE ON [dbo].cs_Feed_GetAll  TO PUBLIC
GO

/***********************************************
* Sproc: cs_Feed_GetAll_ModifiedSince
* File Date: 11/29/2006 10:07:30 AM
***********************************************/
Print 'Creating...cs_Feed_GetAll_ModifiedSince'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Feed_GetAll_ModifiedSince]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Feed_GetAll_ModifiedSince]
GO


CREATE PROC [dbo].cs_Feed_GetAll_ModifiedSince
(
	@Minutes int,
	@SettingsID int
)
AS

SELECT  FeedId,
	Url,
	Title,
	Link,
	Language,
	Generator,
	SubscribeDate,
	LastUpdateDate,
	FeedStateId,
	LastModified,
	ETag
FROM cs_Feed
Where DateAdd(mi, @Minutes, LastUpdateDate) <= GetDate() and SettingsID = @SettingsID


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT EXECUTE ON [dbo].cs_Feed_GetAll_ModifiedSince  TO PUBLIC
GO

/***********************************************
* Sproc: cs_Feed_GetFeed
* File Date: 11/29/2006 10:07:31 AM
***********************************************/
Print 'Creating...cs_Feed_GetFeed'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Feed_GetFeed]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Feed_GetFeed]
GO

CREATE PROC [dbo].cs_Feed_GetFeed
	@FeedId INT
AS

SELECT  FeedId,
	Url,
	Title,
	Link,
	Language,
	Generator,
	SubscribeDate,
	LastUpdateDate,
	FeedStateId,
	LastModified,
	ETag
FROM cs_Feed
WHERE FeedId = @FeedId



GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT EXECUTE ON [dbo].cs_Feed_GetFeed  TO PUBLIC
GO

/***********************************************
* Sproc: cs_Feed_GetFeedPosts
* File Date: 11/29/2006 10:07:34 AM
***********************************************/
Print 'Creating...cs_Feed_GetFeedPosts'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Feed_GetFeedPosts]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Feed_GetFeedPosts]
GO


CREATE PROC [dbo].cs_Feed_GetFeedPosts
	@FeedId INT,
	@UserId INT,
	@SettingsID INT
AS

SELECT top 50 fp.FeedPostId,
	fp.FeedId,
	fp.Author,
	fp.Title,
	fp.Description,
	fp.Source,
	fp.GuidName,
	fp.GuidIsPermaLink,
	fp.Link,
	fp.PubDate,
	fp.CommentsUrl,
	fp.EnclosureUrl,
	fp.EnclosureLength,
	fp.EnclosureType,
	fp.Creator,
	fp.CommentApiUrl,
	fp.CommentRssUrl,
	fp.CommentCount, 
	HasRead = CASE WHEN urp.UserID 
			IS NULL THEN 0 ELSE 1 
		  END 
FROM 
	(SELECT DISTINCT UserID, FeedID FROM cs_FolderFeed) ff 
	INNER JOIN cs_Feed f ON
		ff.FeedId = f.FeedId
	INNER JOIN cs_FeedPost fp ON
		ff.FeedId = fp.FeedId
	LEFT OUTER JOIN cs_UserReadPost urp ON
		fp.FeedPostId	= urp.FeedPostId
	AND ff.UserID		= urp.UserID
WHERE
	ff.UserID = @UserId and f.SettingsID = @SettingsID
AND
  	ff.FeedId = @FeedId
ORDER BY fp.PubDate DESC


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT EXECUTE ON [dbo].cs_Feed_GetFeedPosts  TO PUBLIC
GO

/***********************************************
* Sproc: cs_Feed_GetProperties
* File Date: 11/29/2006 10:07:33 AM
***********************************************/
Print 'Creating...cs_Feed_GetProperties'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Feed_GetProperties]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Feed_GetProperties]
GO

CREATE PROC [dbo].cs_Feed_GetProperties
	@FeedId INT
AS


SELECT 	cf.Url,
	cf.Title,
	cf.Link,
	cf.Language,
	cf.Generator,
	cf.SubscribeDate,
	cf.LastUpdateDate,
	cfs.StateName,
	cfs.Description,
	[SubscribeCount] = (SELECT COUNT(*) FROM cs_FolderFeed WHERE FeedId = cf.FeedId),
	[PostCount] = (SELECT COUNT(*) FROM cs_FeedPost WHERE FeedId = cf.FeedId)
FROM 	cs_Feed cf,
	cs_FeedState cfs
WHERE cf.FeedStateId = cfs.FeedStateId
  AND cf.FeedId = @FeedId


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT EXECUTE ON [dbo].cs_Feed_GetProperties  TO PUBLIC
GO

/***********************************************
* Sproc: cs_Feed_GetUsers
* File Date: 11/29/2006 10:07:31 AM
***********************************************/
Print 'Creating...cs_Feed_GetUsers'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Feed_GetUsers]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Feed_GetUsers]
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

CREATE PROC [dbo].cs_Feed_GetUsers
	@SettingsID INT
AS


	SELECT U.*
	FROM  cs_vw_Users_FullUser U
	WHERE U.SettingsID = @SettingsID 
		and U.cs_UserID in (select distinct UserID from cs_Folder where SettingsID = @SettingsID)
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT  EXECUTE  ON [dbo].[cs_Feed_GetUsers]  TO [public]
GO


/***********************************************
* Sproc: cs_Feed_MoveFeed
* File Date: 11/29/2006 10:07:30 AM
***********************************************/
Print 'Creating...cs_Feed_MoveFeed'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Feed_MoveFeed]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Feed_MoveFeed]
GO

CREATE PROC [dbo].cs_Feed_MoveFeed
	@FolderFeedId INT,
	@NewFolderId INT = NULL
AS

UPDATE cs_FolderFeed
SET FolderId = @NewFolderId
WHERE FolderFeedId = @FolderFeedId


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT EXECUTE ON [dbo].cs_Feed_MoveFeed  TO PUBLIC
GO

/***********************************************
* Sproc: cs_Feed_Update
* File Date: 11/29/2006 10:07:30 AM
***********************************************/
Print 'Creating...cs_Feed_Update'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Feed_Update]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Feed_Update]
GO

CREATE PROC [dbo].cs_Feed_Update
	@FeedId INT,
	@Url NVARCHAR(255),
	@Title NVARCHAR(255),
	@Link NVARCHAR(255),
	@Language NVARCHAR(10),
	@Generator NVARCHAR(255),
	@SubscribeDate DATETIME,
	@LastUpdateDate DATETIME,
	@FeedStateId INT,
	@LastModified DATETIME,
	@ETag nvarchar(256) = NULL

AS

UPDATE cs_Feed
SET 	Url = @Url,
	Title = @Title,
	Link = @Link,
	Language = @Language,
	Generator = @Generator,
	SubscribeDate = @SubscribeDate,
	LastUpdateDate = @LastUpdateDate,
	FeedStateId = @FeedStateId,
	LastModified = @LastModified,
	ETag = @ETag
WHERE FeedId = @FeedId


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT EXECUTE ON [dbo].cs_Feed_Update  TO PUBLIC
GO

/***********************************************
* Sproc: cs_Feed_UpdateFeedStatus
* File Date: 11/29/2006 10:07:31 AM
***********************************************/
Print 'Creating...cs_Feed_UpdateFeedStatus'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Feed_UpdateFeedStatus]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Feed_UpdateFeedStatus]
GO



CREATE PROC [dbo].cs_Feed_UpdateFeedStatus
	@FeedId INT,
	@FeedStateId INT
AS


UPDATE cs_Feed
SET	FeedStateId = @FeedStateId,
	LastUpdateDate = GetDate()
WHERE FeedId = @FeedId



GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT EXECUTE ON [dbo].cs_Feed_UpdateFeedStatus  TO PUBLIC
GO

/***********************************************
* Sproc: cs_Folder_AddFolder
* File Date: 11/29/2006 10:07:30 AM
***********************************************/
Print 'Creating...cs_Folder_AddFolder'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Folder_AddFolder]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Folder_AddFolder]
GO


CREATE PROC [dbo].cs_Folder_AddFolder
	@UserID INT,
	@FolderName NVARCHAR(50),
	@ParentFolderId INT = NULL,
	@SettingsID INT,
	@FolderId INT OUTPUT
AS

INSERT INTO cs_Folder
(
	UserId,
	FolderName,
	ParentFolderId,
	SettingsID
	
)
VALUES
(
	@UserId,
	@FolderName,
	@ParentFolderId,
	@SettingsID
)

SELECT @FolderId = @@IDENTITY


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT EXECUTE ON [dbo].cs_Folder_AddFolder  TO PUBLIC
GO

/***********************************************
* Sproc: cs_Folder_DeleteFolder
* File Date: 11/29/2006 10:07:30 AM
***********************************************/
Print 'Creating...cs_Folder_DeleteFolder'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Folder_DeleteFolder]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Folder_DeleteFolder]
GO


CREATE PROC [dbo].cs_Folder_DeleteFolder
	@FolderId INT
AS

-- First, let's delete any associated feeds.
DELETE
FROM cs_FolderFeed
WHERE FolderId = @FolderId

-- Now, delete the folder.
DELETE
FROM cs_Folder
WHERE FolderId = @FolderId


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT EXECUTE ON [dbo].cs_Folder_DeleteFolder  TO PUBLIC
GO

/***********************************************
* Sproc: cs_Folder_GetFeeds
* File Date: 11/29/2006 10:07:31 AM
***********************************************/
Print 'Creating...cs_Folder_GetFeeds'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Folder_GetFeeds]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Folder_GetFeeds]
GO

CREATE PROC [dbo].cs_Folder_GetFeeds
	@UserId INT,
	@SettingsID int,
	@FolderId INT = NULL

AS


IF (@FolderId IS NULL)
  BEGIN

    SELECT  cf1.FeedId,
	    cf1.Url,
	    cf1.Title,
	    cf1.Link,
	    cf1.ETag,
	    cf1.LastModified,
	    cf1.Language,
	    cf1.Generator,
	    cf1.SubscribeDate,
	    cf1.LastUpdateDate,
	    cf1.FeedStateId,
	    cff.FolderFeedId
		,[UnreadCount] = ( select count(*) from (Select top 50 f.FeedPostID, f.FeedId FROM cs_FeedPost f where f.FeedId = cf1.FeedId order by PubDate DESC) fp left outer join cs_UserReadPost urp on fp.FeedPostID = urp.FeedPostID where fp.FeedId = cff.FeedId and urp.UserId IS NULL )
    FROM    cs_Feed AS cf1,
    	    cs_FolderFeed AS cff
    WHERE cff.FeedId = cf1.FeedId
      AND cff.UserId = @UserId
      AND cff.FolderId IS NULL 
      AND cf1.SettingsID = @SettingsID
    ORDER BY cf1.Title

  END

ELSE
  BEGIN

    SELECT  cf1.FeedId,
	    cf1.Url,
	    cf1.Title,
	    cf1.Link,
	    cf1.Language,
	    cf1.Generator,
	    cf1.ETag,
	    cf1.LastModified,
	    cf1.SubscribeDate,
	    cf1.LastUpdateDate,
	    cf1.FeedStateId,
	    cff.FolderFeedId
		,[UnreadCount] = ( select  count(*) from (Select top 50 f.FeedPostID, f.FeedId FROM cs_FeedPost f where f.FeedId = cf1.FeedId order by PubDate DESC) fp left outer join cs_UserReadPost urp on fp.FeedPostID = urp.FeedPostID where fp.FeedId = cff.FeedId and urp.UserId IS NULL )
    FROM    cs_Feed AS cf1,
    	    cs_FolderFeed AS cff
    WHERE cff.FeedId = cf1.FeedId
      AND cff.UserId = @UserId
      AND cff.FolderId = @FolderId 
      AND cf1.SettingsID = @SettingsID
    ORDER BY cf1.Title

END



GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT EXECUTE ON [dbo].cs_Folder_GetFeeds  TO PUBLIC
GO

/***********************************************
* Sproc: cs_Folder_GetFolders
* File Date: 11/29/2006 10:07:34 AM
***********************************************/
Print 'Creating...cs_Folder_GetFolders'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Folder_GetFolders]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Folder_GetFolders]
GO


CREATE PROC [dbo].cs_Folder_GetFolders
	@UserId INT,
	@SettingsID INT,
	@ParentFolderId INT = -1
AS
Begin


	Create Table #Temp ( FeedId int, FolderId int, CNT int )
	
	Insert #Temp (FeedId, FolderId, CNT)
	Select FeedId, cf.FolderId,
	(
		select count(*) from (Select top 50 f.FeedPostID, f.FeedId FROM cs_FeedPost f where f.FeedId = cf.FeedId order by PubDate DESC) fp left outer join cs_UserReadPost urp on fp.FeedPostID = urp.FeedPostID where fp.FeedId = cf.FeedId and urp.UserId IS NULL
	) as [CNT] FROM cs_FolderFeed cf, cs_Folder ff where cf.FolderId = ff.FolderId and  IsNull(ff.ParentFolderId, -1) = @ParentFolderId and cf.UserId = @UserId and cf.SettingsID = @SettingsID and ff.SettingsID = @SettingsID


	SELECT 	FolderId,
		UserId,
		FolderName,
		ParentFolderId
		,[UnreadCount] = (Select Sum(CNT) FROM #Temp where #Temp.FolderId = cs_Folder.FolderID)
	FROM cs_Folder
	WHERE UserId = @UserId
	  AND IsNull(ParentFolderId,-1) =  @ParentFolderId
          AND cs_Folder.SettingsID = @SettingsID
	ORDER BY FolderName



	DROP Table #Temp

  END



GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT EXECUTE ON [dbo].cs_Folder_GetFolders  TO PUBLIC
GO

/***********************************************
* Sproc: cs_Folder_GetSummary
* File Date: 11/29/2006 10:07:34 AM
***********************************************/
Print 'Creating...cs_Folder_GetSummary'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Folder_GetSummary]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Folder_GetSummary]
GO

CREATE PROC [dbo].cs_Folder_GetSummary
	@UserId INT,
	@SettingsID INT,
	@FolderId INT = NULL

AS
BEGIN

IF (@FolderId IS NULL)
BEGIN
	SET @FolderId = -1
END

-- Give me the top 10 most active blog posts
SELECT 	TOP 10
	fp.FeedPostId,
	fp.FeedId,
	fp.Author,
	fp.Title,
	fp.Description,
	fp.Source,
	fp.GuidName,
	fp.GuidIsPermaLink,
	fp.Link,
	fp.PubDate,
	fp.CommentsUrl,
	fp.EnclosureUrl,
	fp.EnclosureLength,
	fp.EnclosureType,
	fp.Creator,
	fp.CommentApiUrl,
	fp.CommentRssUrl,
	fp.CommentCount
FROM 	cs_Feed f,
	cs_FeedPost fp,
	cs_FolderFeed ff
WHERE f.FeedId = fp.FeedId
  AND fp.CommentCount > 0
  AND fp.PubDate >= DATEADD(day, -30, GetDate())
  AND f.FeedId = ff.FeedId
  AND ff.UserId = @UserId
  AND IsNull(ff.FolderId,-1) = @FolderId
  AND f.SettingsID = @SettingsID AND ff.SettingsID = @SettingsID
  ORDER BY fp.CommentCount DESC



SELECT top 100 	fp.FeedPostId,
	fp.FeedId,
	fp.Author,
	fp.Title,
	fp.Description,
	fp.Source,
	fp.GuidName,
	fp.GuidIsPermaLink,
	fp.Link,
	fp.PubDate,
	fp.CommentsUrl,
	fp.EnclosureUrl,
	fp.EnclosureLength,
	fp.EnclosureType,
	fp.Creator,
	fp.CommentApiUrl,
	fp.CommentRssUrl,
	fp.CommentCount
FROM 	cs_Feed f,
	cs_FeedPost fp,
	cs_FolderFeed ff
WHERE f.FeedId = fp.FeedId
  AND f.FeedId = ff.FeedId
  AND ff.UserId = @UserId
   AND IsNull(ff.FolderId,-1) = @FolderId
  AND f.SettingsID = @SettingsID AND ff.SettingsID = @SettingsID
  ORDER BY fp.PubDate DESC




  END



GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT EXECUTE ON [dbo].cs_Folder_GetSummary  TO PUBLIC
GO

/***********************************************
* Sproc: cs_Folder_MoveFolder
* File Date: 11/29/2006 10:07:31 AM
***********************************************/
Print 'Creating...cs_Folder_MoveFolder'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Folder_MoveFolder]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Folder_MoveFolder]
GO

CREATE PROC [dbo].cs_Folder_MoveFolder
	@FolderId INT,
	@NewParentFolderId INT = NULL
AS

UPDATE cs_Folder
SET ParentFolderId = @NewParentFolderId
WHERE FolderId = @FolderId


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT EXECUTE ON [dbo].cs_Folder_MoveFolder  TO PUBLIC
GO

/***********************************************
* Sproc: cs_Folder_RenameFolder
* File Date: 11/29/2006 10:07:30 AM
***********************************************/
Print 'Creating...cs_Folder_RenameFolder'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Folder_RenameFolder]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Folder_RenameFolder]
GO

CREATE PROC [dbo].cs_Folder_RenameFolder
	@FolderId INT,
	@FolderName NVARCHAR(50)
AS


UPDATE cs_Folder
SET FolderName = @FolderName
WHERE FolderId = @FolderId



GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT EXECUTE ON [dbo].cs_Folder_RenameFolder  TO PUBLIC
GO

/***********************************************
* Sproc: cs_ForumPostActivityReportRecords_Get
* File Date: 11/29/2006 10:07:31 AM
***********************************************/
Print 'Creating...cs_ForumPostActivityReportRecords_Get'

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_ForumPostActivityReportRecords_Get]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_ForumPostActivityReportRecords_Get]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO


/* Most active forums for a given month: Forum, Total Posts, Replies */
CREATE PROC dbo.cs_ForumPostActivityReportRecords_Get
(
	@BegReportDate datetime,
	@EndReportDate datetime,
	@nRecordNumberStart int,
	@nRecordNumberEnd int,
	@Paged bit
)
AS

BEGIN
IF @Paged = 1
	BEGIN
		DECLARE @totalRecords INT
	
		--------------------------------------------------------------------
	    	-- Define the table to do the filtering and paging
	    	--------------------------------------------------------------------
	    	DECLARE @tblTempData TABLE
	        (
	        	nID INT IDENTITY,
	        	SectionID int,
			ApplicationKey nvarchar(256),
			[Name] nvarchar(255),
			Threads int,
			Replies int,
			Users int
	        )
		INSERT INTO @tblTempData
		(
	        	SectionID, ApplicationKey, [Name], Threads, Replies, Users
	        )
		SELECT * FROM
		    	(SELECT DISTINCT 
			s.SectionID,
			s.ApplicationKey,
			s.[Name],
			(SELECT COUNT(*) FROM cs_Threads t WHERE t.SectionID = s.SectionID AND t.ThreadDate BETWEEN @BegReportDate AND @EndReportDate ) AS Threads,
			(SELECT COUNT(*) FROM cs_Posts p WHERE p.SectionID = s.SectionID  AND p.PostDate BETWEEN @BegReportDate AND @EndReportDate) AS Replies,
			(SELECT COUNT(*) FROM (SELECT DISTINCT UserID FROM cs_Posts p WHERE p.SectionID = s.SectionID  AND p.PostDate BETWEEN @BegReportDate AND @EndReportDate) AS u) AS Users
				FROM cs_Sections s
				WHERE s.ApplicationType = 0
			) AS tr
		WHERE tr.Threads > 0 or tr.Replies > 0
		ORDER BY tr.Replies DESC

		SET @totalRecords = @@rowcount
	        ---------------------------------------------------------------------------------------------------------------------------------------
		SELECT
	        	SectionID, ApplicationKey, [Name], Threads, Replies, Users
	    	FROM
			@tblTempData 
	    	WHERE
			nID BETWEEN @nRecordNumberStart AND @nRecordNumberEnd
	    	ORDER BY 
	        	nID ASC
	
		-- Return totalRecords
		SELECT @totalRecords
	END
ELSE
	BEGIN
		SELECT * FROM
		    	(SELECT DISTINCT 
			s.SectionID,
			s.ApplicationKey,
			s.[Name],
			(SELECT COUNT(*) FROM cs_Threads t WHERE t.SectionID = s.SectionID AND t.ThreadDate BETWEEN @BegReportDate AND @EndReportDate ) AS Threads,
			(SELECT COUNT(*) FROM cs_Posts p WHERE p.SectionID = s.SectionID  AND p.PostDate BETWEEN @BegReportDate AND @EndReportDate) AS Replies,
			(SELECT COUNT(*) FROM (SELECT DISTINCT UserID FROM cs_Posts p WHERE p.SectionID = s.SectionID  AND p.PostDate BETWEEN @BegReportDate AND @EndReportDate) AS u) AS Users
				FROM cs_Sections s
				WHERE s.ApplicationType = 0
			) AS tr
		WHERE tr.Threads > 0 or tr.Replies > 0
		ORDER BY tr.Replies DESC
	END
END



GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_ForumPostActivityReportRecords_Get] to public
go
/***********************************************
* Sproc: cs_forums_GetForumMessages
* File Date: 11/29/2006 10:07:33 AM
***********************************************/
Print 'Creating...cs_forums_GetForumMessages'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_forums_GetForumMessages]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_forums_GetForumMessages]
GO


CREATE procedure [dbo].cs_forums_GetForumMessages
(
	@MessageID int = 0,
	@SettingsID int
)
AS
SET Transaction Isolation Level Read UNCOMMITTED

IF @MessageID = 0
	SELECT 
		*
	FROM
		cs_Messages where SettingsID = @SettingsID
ELSE
	SELECT 
		*
	FROM
		cs_Messages
	WHERE
		MessageID = @MessageID and SettingsID = @SettingsID






















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].cs_forums_GetForumMessages to public
go
/***********************************************
* Sproc: cs_forums_GetForumModerators
* File Date: 11/29/2006 10:07:34 AM
***********************************************/
Print 'Creating...cs_forums_GetForumModerators'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_forums_GetForumModerators]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_forums_GetForumModerators]
GO

CREATE  PROCEDURE [dbo].cs_forums_GetForumModerators
(
	@SectionID	int,
	@SettingsID int
)
 AS
SET Transaction Isolation Level Read UNCOMMITTED
	-- get a list of forum moderators
	SELECT 
		UserName, EmailNotification, DateCreated
	FROM 
		Moderators (nolock)
	WHERE 
		(SectionID = @SectionID OR SectionID = 0) and SettingsID = @SettingsID

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].cs_forums_GetForumModerators to public
go
/***********************************************
* Sproc: cs_forums_GetForumsModeratedByUser
* File Date: 11/29/2006 10:07:32 AM
***********************************************/
Print 'Creating...cs_forums_GetForumsModeratedByUser'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_forums_GetForumsModeratedByUser]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_forums_GetForumsModeratedByUser]
GO






create procedure [dbo].cs_forums_GetForumsModeratedByUser
(
	@UserName	nvarchar(50),
	@SettingsID int
)
 AS
SET Transaction Isolation Level Read UNCOMMITTED
	-- determine if this user can moderate ALL forums
	IF EXISTS(SELECT NULL FROM Moderators (nolock) WHERE SectionID = 0 AND Username = @UserName and SettingsID = @SettingsID)
		SELECT SectionID, ForumName = 'All Forums', EmailNotification, DateCreated FROM Moderators (nolock)
		WHERE SectionID = 0 AND Username = @UserName and SettingsID = @SettingsID
	ELSE
		-- get all of the forums moderated by this particular user
		SELECT
			M.SectionID,
			EmailNotification,
			ForumName = F.Name,
			M.DateCreated
		FROM Moderators M (nolock)
			INNER JOIN Forums F (nolock) ON
				F.SectionID = M.SectionID
		WHERE Username = @UserName and M.SettingsID = @SettingsID  and F.SettingsID = @SettingsID

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].cs_forums_GetForumsModeratedByUser to public
go
/***********************************************
* Sproc: cs_forums_GetForumsNotModeratedByUser
* File Date: 11/29/2006 10:07:31 AM
***********************************************/
Print 'Creating...cs_forums_GetForumsNotModeratedByUser'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_forums_GetForumsNotModeratedByUser]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_forums_GetForumsNotModeratedByUser]
GO

CREATE  PROCEDURE [dbo].cs_forums_GetForumsNotModeratedByUser
(
	@UserName	nvarchar(50),
	@SettingsID int
)
 AS
SET Transaction Isolation Level Read UNCOMMITTED
	-- determine if this user can moderate ALL forums
	IF NOT EXISTS(SELECT NULL FROM Moderators (nolock) WHERE SectionID = 0 AND Username = @UserName and SettingsID = @SettingsID)
		-- get all of the forums NOT moderated by this particular user
		SELECT SectionID =  0, ForumName =  'All Forums'
		UNION
		SELECT
			SectionID,
			ForumName = F.Name
		FROM Forums F (nolock) 
		WHERE SettingsID = @SettingsID and  SectionID NOT IN (SELECT SectionID FROM Moderators (nolock) WHERE Username = @UserName and SettingsID = @SettingsID)


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_forums_GetForumsNotModeratedByUser] to public
go
/***********************************************
* Sproc: cs_forums_GetUnmoderatedPostStatus
* File Date: 11/29/2006 10:07:32 AM
***********************************************/
Print 'Creating...cs_forums_GetUnmoderatedPostStatus'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_forums_GetUnmoderatedPostStatus]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_forums_GetUnmoderatedPostStatus]
GO

CREATE PROCEDURE [dbo].cs_forums_GetUnmoderatedPostStatus
(
  @SectionID int = null,
  @UserName varchar,
  @SettingsID int
)
AS
SET Transaction Isolation Level Read UNCOMMITTED
IF(@SectionID = 0)
     SET @SectionID  = null

IF(@SectionID IS Null)
BEGIN
     SELECT OldestPostAgeInMinutes = DateDiff(mi, IsNull(MIN(PostDate),GetDate()),GetDate()),TotalPostsInModerationQueue = Count(PostID)
     FROM cs_Posts P 
     WHERE P.IsApproved = 0 
     AND P.SettingsID = @SettingsID
END
ELSE
BEGIN
     SELECT OldestPostAgeInMinutes = DateDiff(mi, IsNull(MIN(PostDate),GetDate()),GetDate()),TotalPostsInModerationQueue = Count(PostID)
     FROM cs_Posts P 
     WHERE P.IsApproved = 0 
     AND P.SettingsID = @SettingsID
     AND P.SectionID = @SectionID
END
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_forums_GetUnmoderatedPostStatus] to public
go
/***********************************************
* Sproc: cs_forums_Moderate_PostSet
* File Date: 11/29/2006 10:07:31 AM
***********************************************/
Print 'Creating...cs_forums_Moderate_PostSet'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_forums_Moderate_PostSet]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_forums_Moderate_PostSet]
GO





CREATE PROCEDURE dbo.cs_forums_Moderate_PostSet
(
	@SectionID		int,
	@PageIndex 		int,
	@PageSize 		int,
	@SortBy 		int,
	@SortOrder 		bit,
	@UserID 		int,
	@ReturnRecordCount 	bit,
	@SettingsID		int
)
AS
SET Transaction Isolation Level Read UNCOMMITTED
BEGIN

DECLARE @PageLowerBound int
DECLARE @PageUpperBound int
DECLARE @ThreadID int

-- Set the page bounds
SET @PageLowerBound = @PageSize * @PageIndex
SET @PageUpperBound = @PageLowerBound + @PageSize + 1

-- Create a temp table to store the select results
CREATE TABLE #PageIndex 
(
	IndexID int IDENTITY (1, 1) NOT NULL,
	PostID int
)

-- Sort by Post Date
IF @SortBy = 0 AND @SortOrder = 0
    INSERT INTO #PageIndex (PostID)
    SELECT PostID FROM cs_Posts P (nolock) WHERE IsApproved = 0 AND SectionID = @SectionID and SettingsID = @SettingsID ORDER BY PostDate

ELSE IF @SortBy = 0 AND @SortOrder = 1
    INSERT INTO #PageIndex (PostID)
    SELECT PostID FROM cs_Posts P (nolock) WHERE IsApproved = 0 AND SectionID = @SectionID and SettingsID = @SettingsID ORDER BY PostDate DESC

-- Select the individual posts
SELECT
	P.PostID, P.ThreadID, P.ParentID, P.PostAuthor, P.UserID, P.SectionID, P.PostLevel, P.SortOrder, P.Subject, P.PostDate, P.IsApproved,
	P.IsLocked, P.IsIndexed, P.TotalViews, P.Body, P.FormattedBody, P.IPAddress, P.PostType, P.PostMedia, P.EmoticonID, P.SettingsID, P.AggViews,
	P.PropertyNames as PostPropertyNames, P.PropertyValues as PostPropertyValues,
	P.PostConfiguration,P.UserTime, P.ApplicationPostType, P.PostName, P.PostStatus, P.SpamScore,
	P.Points as PostPoints, P.RatingSum as PostRatingSum, P.TotalRatings as PostTotalRatings,
	T.*, U.*, #PageIndex.*,
	T.IsLocked,
	T.IsSticky,
	Username = P.PostAuthor,
	EditNotes = (SELECT EditNotes FROM cs_PostEditNotes WHERE PostID = P.PostID),
	AttachmentFilename = ISNULL ( (SELECT [FileName] FROM cs_PostAttachments WHERE PostID = P.PostID), ''),
	Replies = (SELECT COUNT(P2.PostID) FROM cs_Posts P2 (nolock) WHERE P2.ParentID = P.PostID AND P2.PostLevel != 1),
	IsModerator = (SELECT count(UserID) from cs_Moderators where UserID = @UserID),
	HasRead = 0 -- not used
FROM 
	cs_Posts P (nolock),
	cs_Threads T,
	cs_vw_Users_FullUser U,
	#PageIndex
WHERE 
	P.PostID = #PageIndex.PostID AND
	P.UserID = U.cs_UserID AND
	T.ThreadID = P.ThreadID AND
	#PageIndex.IndexID > @PageLowerBound AND
	#PageIndex.IndexID < @PageUpperBound and U.SettingsID = @SettingsID
ORDER BY
	IndexID
END



GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT  EXECUTE  ON [dbo].[cs_forums_Moderate_PostSet]  TO [public]
GO


/***********************************************
* Sproc: cs_forums_Post
* File Date: 11/29/2006 10:07:32 AM
***********************************************/
Print 'Creating...cs_forums_Post'

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_forums_Post]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_forums_Post]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO



CREATE PROCEDURE dbo.cs_forums_Post
(
	@PostID int,
	@UserID int,
	@TrackViews bit,
	@SettingsID int,
	@MarkRead bit = 0,
	@IncludeCategories bit = 0
) 
AS
/*
	Procedure for getting basic information on a single post.
*/
SET Transaction Isolation Level Read UNCOMMITTED

DECLARE @NextThreadID int
DECLARE @PrevThreadID int
DECLARE @ThreadID int 
DECLARE @SectionID int
DECLARE @SortOrder int
DECLARE @IsApproved bit
DECLARE @IsAnonymousUser bit

SELECT 
	@ThreadID = ThreadID, 
	@SectionID = SectionID, 
	@SortOrder=SortOrder,
	@IsApproved = IsApproved
FROM 
	cs_Posts (nolock) 
WHERE 
	PostID = @PostID and SettingsID = @SettingsID

-- Do we have an anonymous user?
SET @IsAnonymousUser = (SELECT IsAnonymous FROM cs_vw_Users_FullUser WHERE cs_UserID = @UserID and SettingsID = @SettingsID)

-- Is the Forum 0 (If so this is a private message and we need to verify the user can view it
IF @SectionID = 0
BEGIN
	IF NOT EXISTS (SELECT UserID FROM cs_PrivateMessages WHERE UserID = @UserID AND ThreadID = @ThreadID)
		RETURN
END

DECLARE @TrackingThread bit

IF @TrackViews = 1
BEGIN
	-- Update the counter for the number of times this post is viewed
	UPDATE cs_Posts SET TotalViews = (TotalViews + 1) WHERE PostID = @PostID and SettingsID = @SettingsID
	UPDATE cs_Threads SET TotalViews = (TotalViews + 1) WHERE ThreadID = @ThreadID and SettingsID = @SettingsID
END

-- Mark the post as read if this user is not anonymous
IF @MarkRead = 1 AND @IsAnonymousUser = 0 AND @IsApproved = 1
BEGIN
	IF NOT EXISTS (SELECT ThreadID FROM cs_ThreadsRead WHERE ThreadID = @ThreadID AND UserID = @UserID and SettingsID = @SettingsID and SectionID = @SectionID)
		INSERT INTO cs_ThreadsRead (UserID, ThreadID, SectionID, SettingsID) VALUES (@UserID, @ThreadID, @SectionID, @SettingsID)
END

/*
-- get the anonymous user id for this site
if( @UserID = 0 ) 
BEGIN
	exec cs_GetAnonymousUserID @SettingsID, @UserID output
END


IF EXISTS(SELECT ThreadID FROM cs_TrackedThreads (nolock) WHERE ThreadID = @ThreadID AND UserID=@UserID)
	SELECT @TrackingThread = 1
ELSE
	SELECT @TrackingThread = 0
*/

-- Get tracking thread information
IF (@IsAnonymousUser = 0) AND EXISTS(SELECT ThreadID FROM cs_TrackedThreads WHERE ThreadID = @ThreadID AND UserID=@UserID)
	SET @TrackingThread = 1
ELSE
	SET @TrackingThread = 0

SELECT
	P.PostID, P.ThreadID, P.ParentID, P.PostAuthor, P.UserID, P.SectionID, P.PostLevel, P.SortOrder, P.Subject, P.PostDate, P.IsApproved,
	P.IsLocked, P.IsIndexed, P.TotalViews, P.Body, P.FormattedBody, P.IPAddress, P.PostType, P.PostMedia, P.EmoticonID, P.SettingsID, P.AggViews,
	P.PostPropertyNames as PostPropertyNames, P.PostPropertyValues as PostPropertyValues,
	P.PostConfiguration,P.UserTime, P.ApplicationPostType, P.PostName, P.PostStatus, P.SpamScore,
	P.Points as PostPoints, P.RatingSum as PostRatingSum, P.TotalRatings as PostTotalRatings,
	U.*, P.PostAuthor as [Username],
	T.ThreadDate,
	T.StickyDate,
	T.IsLocked,
	T.IsSticky,
	T.RatingSum,
	T.TotalRatings,
	HasRead = 0,
	EditNotes = (SELECT EditNotes FROM cs_PostEditNotes WHERE PostID = P.PostID),
	IndexInThread = (SELECT Count(PostID) FROM cs_Posts P1 WHERE IsApproved = 1 AND ThreadID = @ThreadID AND SortOrder <= (SELECT SortOrder FROM cs_Posts where PostID = @PostID)),
	AttachmentFilename,ContentType, IsRemote, FriendlyFileName, ContentSize, [FileName],p.Created, Height, Width,
--	AttachmentFilename = ISNULL ( (SELECT [FileName] FROM cs_PostAttachments WHERE PostID = P.PostID), ''),
	IsModerator = (SELECT Count(*) FROM cs_Moderators WHERE UserID = U.cs_UserID),
	Replies = (SELECT COUNT(*) FROM cs_Posts P2 (nolock) WHERE P2.ParentID = P.PostID AND P2.PostLevel != 1),
	PrevThreadID = 0,
	NextThreadID = 0,
	UserIsTrackingThread = @TrackingThread
FROM 
	cs_vw_PostsWithAttachmentDetails P,
	--cs_Posts P,
	cs_Threads T,
	cs_vw_Users_FullUser U
WHERE 
	P.PostID = @PostID AND
	P.ThreadID = T.ThreadID AND
	P.UserID = U.cs_UserID and P.SettingsID = @SettingsID and U.SettingsID = @SettingsID


IF @IncludeCategories = 1
BEGIN
	SELECT 
		Cats.[Name]
	FROM 
		cs_Posts_InCategories PIC
		JOIN cs_Post_Categories Cats ON PIC.CategoryID = Cats.CategoryID
	WHERE 
		PIC.PostID = @PostID
End
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT  EXECUTE  ON [dbo].[cs_forums_Post]  TO [public]
GO


/***********************************************
* Sproc: cs_forums_Posts_PostSet
* File Date: 11/29/2006 10:07:33 AM
***********************************************/
Print 'Creating...cs_forums_Posts_PostSet'

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_forums_Posts_PostSet]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_forums_Posts_PostSet]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO







CREATE PROCEDURE dbo.cs_forums_Posts_PostSet
(
	@PostID	int,
	@PageIndex int,
	@PageSize int,
	@SortBy int,
	@SortOrder bit,
	@UserID int,
	@ReturnRecordCount bit,
	@AllowUnapproved bit = 0,
	@SettingsID int,
	@IncludeCategories bit = 0
)
AS
SET Transaction Isolation Level Read UNCOMMITTED
BEGIN

DECLARE @PageLowerBound int
DECLARE @PageUpperBound int
DECLARE @ThreadID int
DECLARE @SectionID int

-- First set the rowcount
DECLARE @RowsToReturn int
SET @RowsToReturn = @PageSize * (@PageIndex + 1)
SET ROWCOUNT @RowsToReturn

-- Set the page bounds
SET @PageLowerBound = @PageSize * @PageIndex
SET @PageUpperBound = @PageLowerBound + @PageSize + 1

-- Get the ThreadID
SELECT
	@ThreadID = ThreadID,
	@SectionID = SectionID
FROM 
	cs_Posts 
WHERE 
	PostID = @PostID and SettingsID = @SettingsID

-- Is the Forum 0 (If so this is a private message and we need to verify the user can view it
IF @SectionID = 0
BEGIN
	IF NOT EXISTS (SELECT UserID FROM cs_PrivateMessages WHERE UserID = @UserID AND ThreadID = @ThreadID AND SettingsID = @SettingsID)
		RETURN
END

-- Create a temp table to store the select results
CREATE TABLE #PageIndex 
(
	IndexID int IDENTITY (1, 1) NOT NULL,
	PostID int
)

-- Sort by Post Date
IF @SortBy = 0 AND @SortOrder = 0
    INSERT INTO #PageIndex (PostID)
    SELECT PostID FROM cs_Posts (nolock) WHERE (IsApproved = 1 OR 1 = @AllowUnapproved) AND ThreadID = @ThreadID and SettingsID = @SettingsID ORDER BY PostDate

ELSE IF @SortBy = 0 AND @SortOrder = 1
    INSERT INTO #PageIndex (PostID)
    SELECT PostID FROM cs_Posts (nolock) WHERE (IsApproved = 1 OR 1 = @AllowUnapproved) AND ThreadID = @ThreadID and SettingsID = @SettingsID  ORDER BY PostDate DESC

-- Sort by Author
IF @SortBy = 1 AND @SortOrder = 0
    INSERT INTO #PageIndex (PostID)
    SELECT PostID FROM cs_Posts (nolock) WHERE (IsApproved = 1 OR 1 = @AllowUnapproved) AND ThreadID = @ThreadID and SettingsID = @SettingsID  ORDER BY UserID

ELSE IF @SortBy = 1 AND @SortOrder = 1
    INSERT INTO #PageIndex (PostID)
    SELECT PostID FROM cs_Posts (nolock) WHERE (IsApproved = 1 OR 1 = @AllowUnapproved) AND ThreadID = @ThreadID and SettingsID = @SettingsID  ORDER BY UserID DESC

-- Sort by SortOrder
IF @SortBy = 2 AND @SortOrder = 0
    INSERT INTO #PageIndex (PostID)
    SELECT PostID FROM cs_Posts (nolock) WHERE (IsApproved = 1 OR 1 = @AllowUnapproved) AND ThreadID = @ThreadID and SettingsID = @SettingsID  ORDER BY SortOrder

ELSE IF @SortBy = 2 AND @SortOrder = 1
    INSERT INTO #PageIndex (PostID)
    SELECT PostID FROM cs_Posts (nolock) WHERE (IsApproved = 1 OR 1 = @AllowUnapproved) AND ThreadID = @ThreadID and SettingsID = @SettingsID  ORDER BY SortOrder DESC

-- Select the individual posts
SELECT
	P.PostID, P.ThreadID, P.ParentID, P.PostAuthor, P.UserID, P.SectionID, P.PostLevel, P.SortOrder, P.Subject, P.PostDate, P.IsApproved,
	P.IsLocked, P.IsIndexed, P.TotalViews, P.Body, P.FormattedBody, P.IPAddress, P.PostType, P.PostMedia, P.EmoticonID, P.SettingsID, P.AggViews,
	P.PropertyNames as PostPropertyNames, P.PropertyValues as PostPropertyValues,
	P.PostConfiguration, P.UserTime, P.ApplicationPostType, P.PostName, P.PostStatus, P.SpamScore,
	P.Points as PostPoints, P.RatingSum as PostRatingSum, P.TotalRatings as PostTotalRatings,
	T.*, U.*, #PageIndex.*,
	T.IsLocked,
	T.IsSticky,
	Username = P.PostAuthor,
	ThreadStarterAuthor = T.PostAuthor,
	ThreadStartDate = T.PostDate,	
	EditNotes = (SELECT EditNotes FROM cs_PostEditNotes WHERE PostID = P.PostID),
	AttachmentFilename = ISNULL ( (SELECT [FileName] FROM cs_PostAttachments WHERE PostID = P.PostID), ''),
	Replies = 0, --not used(SELECT COUNT(P2.PostID) FROM cs_Posts P2 (nolock) WHERE P2.ParentID = P.PostID AND P2.PostLevel != 1),
	IsModerator = 0, -- not used
	HasRead = 0 -- not used
FROM 
	cs_Posts P (nolock),
	cs_Threads T,
	cs_vw_Users_FullUser U,
	#PageIndex
WHERE 
	P.PostID = #PageIndex.PostID AND
	P.UserID = U.cs_UserID AND
	T.ThreadID = P.ThreadID AND
	#PageIndex.IndexID > @PageLowerBound AND
	#PageIndex.IndexID < @PageUpperBound and U.SettingsID = @SettingsID
ORDER BY
	IndexID
END

IF @IncludeCategories = 1
BEGIN
	SELECT 
		Cats.[Name], jP.PostID
	FROM 
		#PageIndex jPI
		JOIN cs_Posts jP ON jPI.PostID = jP.PostID
		JOIN cs_Posts_InCategories PIC ON jP.PostID = PIC.PostID
		JOIN cs_Post_Categories Cats ON PIC.CategoryID = Cats.CategoryID
	WHERE 
		jPI.IndexID > @PageLowerBound
		AND jPI.IndexID < @PageUpperBound
		AND  jP.SettingsID = @SettingsID
End

IF @ReturnRecordCount = 1
  SELECT count(PostID) FROM cs_Posts (nolock) WHERE (IsApproved = 1 OR 1 = @AllowUnapproved) AND ThreadID = @ThreadID  and SettingsID = @SettingsID
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT  EXECUTE  ON [dbo].[cs_forums_Posts_PostSet]  TO [public]
GO


/***********************************************
* Sproc: cs_forums_Search
* File Date: 11/29/2006 10:07:32 AM
***********************************************/
Print 'Creating...cs_forums_Search'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_forums_Search]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_forums_Search]
GO
/***********************************************
* Sproc: cs_forums_Threads_ThreadsRead
* File Date: 11/29/2006 10:07:31 AM
***********************************************/
Print 'Creating...cs_forums_Threads_ThreadsRead'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_forums_threads_ThreadsRead]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_forums_threads_ThreadsRead]
GO



CREATE procedure [dbo].cs_forums_threads_ThreadsRead (
	@SectionID as int,
	@UserID as int,
	@SettingsID as int
)
AS
SET Transaction Isolation Level Read UNCOMMITTED
DECLARE @ReadAfter int

SELECT 
	@ReadAfter = MarkReadAfter 
FROM 
	cs_SectionsRead 
WHERE 
	UserID = @UserID AND 
	SectionID = @SectionID AND
	SettingsID = @SettingsID

IF @ReadAfter IS NOT NULL
	SELECT ThreadID = @ReadAfter
ELSE
	SELECT ThreadID = 0

IF @SectionID = -1
BEGIN
SELECT DISTINCT
	ThreadID
FROM
	cs_ThreadsRead
WHERE
	SettingsID = @SettingsID
	AND UserID = @UserID
END
ELSE
BEGIN
SELECT DISTINCT
	ThreadID
FROM
	cs_ThreadsRead
WHERE
	UserID = @UserID AND
	SectionID = @SectionID AND
	SettingsID = @SettingsID
END
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT  EXECUTE  ON [dbo].[cs_forums_threads_ThreadsRead]  TO [public]
GO


/***********************************************
* Sproc: cs_forums_Thread_Get
* File Date: 11/29/2006 10:07:31 AM
***********************************************/
Print 'Creating...cs_forums_Thread_Get'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_forums_Thread_Get]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_forums_Thread_Get]
GO



CREATE PROCEDURE [dbo].cs_forums_Thread_Get
/*

	Procedure for getting basic information on a single thread.

*/
(
	@ThreadID int,
	@UserID int,
	@SettingsID int
) AS
SET Transaction Isolation Level Read UNCOMMITTED
SELECT
	T.*,
	P.PostID,
	P.Subject,
	P.Body,P.FormattedBody,
	P.PostConfiguration,
	P.PropertyNames as PostPropertyNames,
	P.PropertyValues as PostPropertyValues,
	UserName = T.PostAuthor,
	HasRead =  CASE
		WHEN @UserID = 0 THEN 0
		WHEN @UserID > 0 THEN (Select Convert(bit,Count(*)) FROM cs_vw_HasReadForum where ((ThreadID is null and MarkReadAfter > p.ThreadID) or (MarkReadAfter is null and ThreadID = p.ThreadID)) and UserID = @UserID and SectionID = p.SectionID)
		END
FROM 
	cs_Posts P,
	cs_Threads T,
	cs_vw_Users_FullUser U
WHERE 
	P.PostID = P.ParentID AND
	P.ThreadID = @ThreadID AND
	T.ThreadID = P.ThreadID AND
	P.UserID = U.cs_UserID and P.SettingsID = @SettingsID


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].cs_forums_Thread_Get to public
go
/***********************************************
* Sproc: cs_fourm_Feedback_Get
* File Date: 11/29/2006 10:07:31 AM
***********************************************/
Print 'Creating...cs_fourm_Feedback_Get'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_fourm_Feedback_Get]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_fourm_Feedback_Get]
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

/***********************************************
* Sproc: cs_gallery_Post_GetSortOrder
* File Date: 11/29/2006 10:07:33 AM
***********************************************/
Print 'Creating...cs_gallery_Post_GetSortOrder'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_gallery_Post_GetSortOrder]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_gallery_Post_GetSortOrder]
GO


/***********************************************
* Sproc: cs_gallery_Search
* File Date: 11/29/2006 10:07:31 AM
***********************************************/
Print 'Creating...cs_gallery_Search'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_gallery_Search]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_gallery_Search]
GO
/***********************************************
* Sproc: cs_gallery_Search_PostReindex
* File Date: 11/29/2006 10:07:31 AM
***********************************************/
Print 'Creating...cs_gallery_Search_PostReindex'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_gallery_Search_PostReindex]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_gallery_Search_PostReindex]
GO

/***********************************************
* Sproc: cs_gallery_Threads_GetAllThreads
* File Date: 11/29/2006 10:07:33 AM
***********************************************/
Print 'Creating...cs_gallery_Threads_GetAllThreads'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_gallery_Threads_GetAllThreads]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_gallery_Threads_GetAllThreads]
GO





/***********************************************
* Sproc: cs_gallery_Threads_GetThreadSet
* File Date: 11/29/2006 10:07:31 AM
***********************************************/
Print 'Creating...cs_gallery_Threads_GetThreadSet'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_gallery_Threads_GetThreadSet]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_gallery_Threads_GetThreadSet]
GO

--Replaced by cs_shared_Threads_GetThreadSet
/***********************************************
* Sproc: cs_GetAnonymousUserID
* File Date: 11/29/2006 10:07:30 AM
***********************************************/
Print 'Creating...cs_GetAnonymousUserID'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_GetAnonymousUserID]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_GetAnonymousUserID]
GO


Create Proc [dbo].cs_GetAnonymousUserID
(
	@SettingsID int,
	@UserID int output
)
as
SET Transaction Isolation Level Read UNCOMMITTED
Select @UserID = cs_UserID FROM cs_vw_Users_FullUser where SettingsID = @SettingsID and IsAnonymous = 1

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 

GO

grant execute on [dbo].cs_GetAnonymousUserID to public
go
/***********************************************
* Sproc: cs_GetSectionSubscriptionType
* File Date: 11/29/2006 10:07:30 AM
***********************************************/
Print 'Creating...cs_GetSectionSubscriptionType'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_GetSectionSubscriptionType]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_GetSectionSubscriptionType]
GO


CREATE  procedure [dbo].cs_GetSectionSubscriptionType
(
	@UserID int,
	@SectionID int,
	@SettingsID int,
	@SubType int OUTPUT
)
AS
SET Transaction Isolation Level Read UNCOMMITTED
SELECT SubscriptionType FROM cs_TrackedSections WHERE SectionID=@SectionID AND UserID=@UserID and SettingsID = @SettingsID








GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].cs_GetSectionSubscriptionType to public
go
/***********************************************
* Sproc: cs_GetSectionSubscriptionTypes
* File Date: 11/29/2006 10:07:30 AM
***********************************************/
Print 'Creating...cs_GetSectionSubscriptionTypes'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_GetSectionSubscriptionTypes]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_GetSectionSubscriptionTypes]
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

CREATE  procedure [dbo].cs_GetSectionSubscriptionTypes
(
	@UserID int,
	@SettingsID int
)
AS
SET Transaction Isolation Level Read UNCOMMITTED
SELECT SubscriptionType, SectionID FROM cs_TrackedSections WHERE UserID=@UserID and SettingsID = @SettingsID
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT  EXECUTE  ON [dbo].[cs_GetSectionSubscriptionTypes]  TO [public]
GO


/***********************************************
* Sproc: cs_GetTotalPostCount
* File Date: 11/29/2006 10:07:34 AM
***********************************************/
Print 'Creating...cs_GetTotalPostCount'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_GetTotalPostCount]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_GetTotalPostCount]
GO



CREATE   PROCEDURE [dbo].cs_GetTotalPostCount
(
	@SettingsID int
)

 AS
SET Transaction Isolation Level Read UNCOMMITTED
	SELECT TOP 1 
		TotalPosts 
	FROM 
		forums_Statistics where SettingsID = @SettingsID






GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_GetTotalPostCount] to public
go
/***********************************************
* Sproc: cs_GetUserIDByAppToken
* File Date: 11/29/2006 10:07:32 AM
***********************************************/
Print 'Creating...cs_GetUserIDByAppToken'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_GetUserIDByAppToken]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_GetUserIDByAppToken]
GO




CREATE         PROCEDURE [dbo].cs_GetUserIDByAppToken
(
	@AppUserToken varchar(128),
	@SettingsID int
)
AS
SET Transaction Isolation Level Read UNCOMMITTED
SELECT
	U.cs_UserID
FROM 
	cs_vw_Users_FullUser U (nolock)
WHERE 
	U.cs_AppUserToken = @AppUserToken and SettingsID = @SettingsID






























GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_GetUserIDByAppToken] to public
go
/***********************************************
* Sproc: cs_Groups_Get
* File Date: 11/29/2006 10:07:32 AM
***********************************************/
Print 'Creating...cs_Groups_Get'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Groups_Get]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Groups_Get]
GO

CREATE  PROCEDURE [dbo].cs_Groups_Get
(
	@SettingsID int,
	@ApplicationType smallint = 0,
	@RequireModeration bit = 0

)
AS
SET Transaction Isolation Level Read UNCOMMITTED
BEGIN

	IF (@RequireModeration = 0)
		SELECT
			*
		FROM
			cs_Groups
		WHERE
			(SettingsID = @SettingsID) and ApplicationType = @ApplicationType
	ELSE
		SELECT DISTINCT
			FG.*
		FROM
			cs_Sections S,
			cs_Groups FG
		WHERE
			S.GroupID = FG.GroupID AND
			S.IsActive = 1 AND
			(SELECT Count(PostID) FROM cs_Posts P WHERE SectionID = S.SectionID AND P.IsApproved = 0) > 0 AND
			(FG.SettingsID = @SettingsID) AND
			FG.ApplicationType = @ApplicationType

END


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_Groups_Get] to public
go
/***********************************************
* Sproc: cs_Groups_ReOrder
* File Date: 11/29/2006 10:07:31 AM
***********************************************/
Print 'Creating...cs_Groups_ReOrder'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Groups_ReOrder]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Groups_ReOrder]
GO


Create Proc [dbo].cs_Groups_ReOrder 
(
	@GroupID int,
	@Index int,
	@SettingsID int
	
)

as

Set NoCount On

Declare @ApplicationType int
Select @ApplicationType = ApplicationType From cs_Groups where GroupID = @GroupID and SettingsID = @SettingsID

exec cs_Groups_ResetOrder @ApplicationType, @SettingsID

update cs_Groups
Set SortOrder = SortOrder + 1 where SortOrder >= @Index and SettingsID = @SettingsID and ApplicationType = @ApplicationType

update cs_Groups
Set SortOrder = @Index where GroupID = @GroupID and SettingsID = @SettingsID and ApplicationType = @ApplicationType

exec cs_Groups_ResetOrder @ApplicationType, @SettingsID




GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_Groups_ReOrder] to public
go
/***********************************************
* Sproc: cs_Groups_ResetOrder
* File Date: 11/29/2006 10:07:31 AM
***********************************************/
Print 'Creating...cs_Groups_ResetOrder'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Groups_ResetOrder]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Groups_ResetOrder]
GO

Create Proc [dbo].cs_Groups_ResetOrder
(
	@ApplicationType int,
	@SettingsID int
)
as

Declare @Sort int
Set @Sort = 0
Declare @GroupID int
DECLARE group_Cursor CURSOR FOR
SELECT GroupID FROM cs_Groups where ApplicationType = @ApplicationType and SettingsID = @SettingsID order by SortOrder

OPEN group_Cursor

FETCH NEXT FROM group_Cursor Into @GroupID
WHILE (@@FETCH_STATUS = 0)
Begin
	Update cs_Groups Set SortOrder = @Sort where GroupID = @GroupID
	Set @Sort = @Sort + 1
   FETCH NEXT FROM group_Cursor Into @GroupID
End

CLOSE group_Cursor
DEALLOCATE group_Cursor



GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_Groups_ResetOrder] to public
go
/***********************************************
* Sproc: cs_Group_CreateUpdateDelete
* File Date: 11/29/2006 10:07:30 AM
***********************************************/
Print 'Creating...cs_Group_CreateUpdateDelete'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Group_CreateUpdateDelete]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Group_CreateUpdateDelete]
GO


CREATE       PROCEDURE [dbo].cs_Group_CreateUpdateDelete
(
	@GroupID	int out,
	@Name		nvarchar(256),
	@Description	nvarchar(1000) = '',
	@ApplicationType smallint = 0,
	@Action 	int,
	@SettingsID 	int
)
AS
SET Transaction Isolation Level Read UNCOMMITTED
-- CREATE
IF @Action = 0
BEGIN
	DECLARE @SortOrder int

	SELECT @SortOrder = coalesce(MAX(SortOrder) + 1, 1) FROM cs_Groups where SettingsID = @SettingsID

	-- Create a new forum group
	INSERT INTO 
		cs_Groups 
		(
			Name,
			Description,
			SortOrder,
			ApplicationType,
			SettingsID
		)
	VALUES 
		(
			@Name,
			@Description,
			@SortOrder,
			@ApplicationType,
			@SettingsID
		)
	
	SET @GroupID = @@IDENTITY
END


-- UPDATE
ELSE IF @Action = 1
BEGIN

	IF EXISTS(SELECT GroupID FROM cs_Groups WHERE GroupID = @GroupID)
	BEGIN
		UPDATE
			cs_Groups
		SET
			Name = @Name,
			Description = @Description
		WHERE
			GroupID = @GroupID and SettingsID = @SettingsID
	END

END

-- DELETE
ELSE IF @Action = 2
BEGIN
	DELETE cs_Groups WHERE GroupID = @GroupID and SettingsID = @SettingsID
END


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_Group_CreateUpdateDelete] to public
go
/***********************************************
* Sproc: cs_guestbook_GetPosts
* File Date: 11/29/2006 10:07:31 AM
***********************************************/
Print 'Creating...cs_guestbook_GetPosts'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_guestbook_GetPosts]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_guestbook_GetPosts]
GO



CREATE PROCEDURE dbo.cs_guestbook_GetPosts
(
	@PageIndex int,
	@PageSize int,
	@SortOrder bit,
	@SectionID int,
	@SettingsID int
)
AS
SET Transaction Isolation Level Read UNCOMMITTED
BEGIN

DECLARE @PageLowerBound int
DECLARE @PageUpperBound int
DECLARE @ThreadID int

-- First set the rowcount
DECLARE @RowsToReturn int
SET @RowsToReturn = @PageSize * (@PageIndex + 1)
SET ROWCOUNT @RowsToReturn

-- Set the page bounds
SET @PageLowerBound = @PageSize * @PageIndex
SET @PageUpperBound = @PageLowerBound + @PageSize + 1


-- Create a temp table to store the select results
CREATE TABLE #PageIndex 
(
	IndexID int IDENTITY (1, 1) NOT NULL,
	PostID int
)

-- Sort by Post Date
IF  @SortOrder = 0
    INSERT INTO #PageIndex (PostID)
    SELECT PostID FROM cs_Posts (nolock) WHERE IsApproved = 1 AND SectionID = @SectionID and SettingsID = @SettingsID ORDER BY PostID

ELSE 
    INSERT INTO #PageIndex (PostID)
    SELECT PostID FROM cs_Posts (nolock) WHERE IsApproved = 1 AND SectionID = @SectionID and SettingsID = @SettingsID ORDER BY PostID DESC


-- Select the individual posts
SELECT
	P.PostID, P.ThreadID, P.ParentID, P.PostAuthor, P.UserID, P.SectionID, P.PostLevel, P.SortOrder, P.Subject, P.PostDate, P.IsApproved,
	P.IsLocked, P.IsIndexed, P.TotalViews, P.Body, P.FormattedBody, P.IPAddress, P.PostType, P.EmoticonID, P.SettingsID, P.AggViews,
	P.PropertyNames as PostPropertyNames, P.PropertyValues as PostPropertyValues,
	P.PostConfiguration,
	P.Points as PostPoints, P.RatingSum as PostRatingSum, P.TotalRatings as PostTotalRatings,
	T.*, U.*, #PageIndex.*,
	T.IsLocked,
	T.IsSticky,
	Username = P.PostAuthor,
	EditNotes = (SELECT EditNotes FROM cs_PostEditNotes WHERE PostID = P.PostID),
	AttachmentFilename = '',
	Replies = 0,
	IsModerator = 0,
	HasRead = 0 -- not used
FROM 
	cs_Posts P (nolock),
	cs_Threads T,
	cs_vw_Users_FullUser U,
	#PageIndex
WHERE 
	P.PostID = #PageIndex.PostID AND
	P.UserID = U.cs_UserID AND
	T.ThreadID = P.ThreadID AND
	#PageIndex.IndexID > @PageLowerBound AND
	#PageIndex.IndexID < @PageUpperBound and U.SettingsID = @SettingsID
ORDER BY
	IndexID
END


  SELECT Count(PostID) FROM cs_Posts (nolock) WHERE IsApproved = 1 AND SectionID = @SectionID and SettingsID = @SettingsID

DROP Table #PageIndex



GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT  EXECUTE  ON [dbo].[cs_guestbook_GetPosts]  TO [public]
GO


/***********************************************
* Sproc: cs_guestbook_Post_Create
* File Date: 11/29/2006 10:07:31 AM
***********************************************/
Print 'Creating...cs_guestbook_Post_Create'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_guestbook_Post_Create]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_guestbook_Post_Create]
GO



CREATE   PROCEDURE [dbo].cs_guestbook_Post_Create
(
	@SectionID int,
	@Subject nvarchar(256),
	@UserID int,
	@PostAuthor nvarchar(64) = null,
	@Body ntext,
	@FormattedBody ntext,
	@EmoticonID int = 0,
	@PostType int = 0,
	@PostDate datetime = null,
	@UserHostAddress nvarchar(32),
	@PropertyNames ntext = null,
	@PropertyValues ntext = null,
	@SettingsID int,
	@PostID int out
) 
AS
SET Transaction Isolation Level Read UNCOMMITTED
BEGIN
SET NOCOUNT ON
DECLARE @ThreadID int

-- set the PostDate
IF @PostDate IS NULL
	SET @PostDate = GetDate()

-- set the username
IF @PostAuthor IS NULL
	SELECT 
		@PostAuthor = UserName
	FROM 
		cs_vw_Users_FullUser 
	WHERE 
		cs_UserID = @UserID

-- Do we care about duplicates?

Select @ThreadID = ThreadID FROM cs_Threads Where SectionID = @SectionID


SET NOCOUNT ON
BEGIN TRAN


IF @ThreadID is null
BEGIN


	INSERT cs_Threads 	
	( 
		SectionID,
		PostDate, 
		UserID, 
		PostAuthor, 
		ThreadDate, 
		MostRecentPostAuthor, 
		MostRecentPostAuthorID, 	
		MostRecentPostID, 
		IsLocked, 
		IsApproved,
		IsSticky, 
		StickyDate, 
		ThreadEmoticonID,
		SettingsID 
	)
	VALUES
	( 
		@SectionID, 
		@PostDate, 
		@UserID, 
		@PostAuthor,
		@PostDate,
		@PostAuthor,
		@UserID, 
		0,	-- MostRecentPostID, which we don't know until after post INSERT below.
		0,
		1,
		0,
		@PostDate,
		-1,
		@SettingsID 
	)

	-- Get the new ThreadID
	SELECT 
		@ThreadID = @@IDENTITY
	FROM
		cs_Threads
		
	-- Now we add the new post
	INSERT cs_Posts 
		( SectionID, 
		ThreadID, 
		ParentID, 
		PostLevel, 
		SortOrder, 

		Subject, 
		UserID, 
		PostAuthor, 
		IsApproved, 
		IsLocked, 
		Body, 
		FormattedBody, 
		PostType, 
		PostDate, 
		IPAddress, 
		EmoticonID,
		PropertyNames,
		PropertyValues,
		SettingsID
	        )
	VALUES 
		( @SectionID, 
		@ThreadID, 
		0, 	-- ParentID, which we don't know until after INSERT
		1, 	-- PostLevel, 1 marks start/top/first post in thread.
		1, 	-- SortOrder (not in use at this time)
		@Subject, 
		@UserID, 
		@PostAuthor,
		1, 
		0, 
		@Body, 
		@FormattedBody, 
		@PostType, 
		@PostDate, 
		@UserHostAddress, 
		-1,
		@PropertyNames,
		@PropertyValues,
		@SettingsID )
		

	-- Get the new PostID
	SELECT 
		@PostID = @@IDENTITY

	-- Update the new Thread with the new PostID
	UPDATE 
		cs_Threads
	SET 
		MostRecentPostID = @PostID
	WHERE 
		ThreadID = @ThreadID

END
ELSE BEGIN	-- @ParentID <> 0 means there is a reply to an existing post

	-- Insert the new post
	INSERT cs_Posts 
		( SectionID, 
		ThreadID, 
		ParentID, 
		PostLevel, 
		SortOrder, 
		Subject, 
		UserID, 
		PostAuthor, 
		IsApproved, 
		IsLocked, 
		Body, 
		FormattedBody, 
		PostType, 
		PostDate, 
		IPAddress, 
		EmoticonID,
		PropertyNames,
		PropertyValues,
		SettingsID )
	VALUES 
		( @SectionID, 
		@ThreadID, 
		0, 
		1, 
		0,
		@Subject, 
		@UserID, 
		@PostAuthor, 
		1, 
		0, 
		@Body, 
		@FormattedBody, 
		@PostType, 
		@PostDate, 
		@UserHostAddress, 
		-1,
		@PropertyNames,
		@PropertyValues,
		@SettingsID  )


		-- Grab the new PostID and update the ThreadID's info
		SELECT 
			@PostID = @@IDENTITY 




		UPDATE
			cs_Threads 	
		SET 
			TotalReplies = (SELECT COUNT(*) FROM cs_Posts WHERE ThreadID = @ThreadID)
		WHERE
			ThreadID = @ThreadID
	END
END


COMMIT TRAN

SET NOCOUNT OFF

SELECT @PostID = @PostID






GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





grant execute on [dbo].[cs_guestbook_Post_Create] to public
go
/***********************************************
* Sproc: cs_guestbook_Post_Delete
* File Date: 11/29/2006 10:07:30 AM
***********************************************/
Print 'Creating...cs_guestbook_Post_Delete'

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_guestbook_Post_Delete]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_guestbook_Post_Delete]
GO

CREATE   PROCEDURE [dbo].cs_guestbook_Post_Delete
(
	@SectionID int,
	@PostID int
)

as
SET Transaction Isolation Level Read UNCOMMITTED

Declare @ThreadID int
Select @ThreadID = ThreadID FROM cs_Posts where PostID = @PostID and SectionID = @SectionID

if(@ThreadID is null)
RETURN

Delete FROM cs_Posts where PostID = @PostID and SectionID = @SectionID

UPDATE
	cs_Threads 	
SET 
	TotalReplies = (SELECT COUNT(*) FROM cs_Posts WHERE ThreadID = @ThreadID)
WHERE
	ThreadID = @ThreadID
	
GO

grant execute on [dbo].[cs_guestbook_Post_Delete] to public
go
/***********************************************
* Sproc: cs_Image_CreateUpdateDelete
* File Date: 11/29/2006 10:07:32 AM
***********************************************/
Print 'Creating...cs_Image_CreateUpdateDelete'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Image_CreateUpdateDelete]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Image_CreateUpdateDelete]
GO


/***********************************************
* Sproc: cs_InkData_Add
* File Date: 11/29/2006 10:07:34 AM
***********************************************/
Print 'Creating...cs_InkData_Add'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_InkData_Add]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_InkData_Add]
GO


Create Proc [dbo].[cs_InkData_Add]
(	
	@SectionID int,
	@SettingsID int,
	@UserID int,
	@ApplicationType smallint,
	@Ink NTEXT,
	@DateUpdated datetime,
	@InkID int output
)
as

Insert cs_InkData (UserID, SettingsID, SectionID, Ink, DateUpdated, ApplicationType)
Values (@UserID, @SettingsID, @SectionID, @Ink, @DateUpdated, @ApplicationType)

Select @InkID = @@Identity



GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_InkData_Add] to public
go
/***********************************************
* Sproc: cs_InkData_Delete
* File Date: 11/29/2006 10:07:31 AM
***********************************************/
Print 'Creating...cs_InkData_Delete'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_InkData_Delete]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_InkData_Delete]
GO

Create Proc [dbo].[cs_InkData_Delete]
(
	@InkID int,
	@SectionID int,
	@SettingsID int
)

as

Delete FROM cs_InkData Where SettingsID = @SettingsID and SectionID = @SectionID and InkID = @InkID





GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_InkData_Delete] to public
go
/***********************************************
* Sproc: cs_InkData_Get
* File Date: 11/29/2006 10:07:31 AM
***********************************************/
Print 'Creating...cs_InkData_Get'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_InkData_Get]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_InkData_Get]
GO

Create Proc [dbo].[cs_InkData_Get]
(
	@InkID int,
	@SettingsID int
)
as
Select InkID, Ink, UserID, SectionID, SettingsID, DateUpdated, ApplicationType FROM cs_InkData where InkID = @InkID and SettingsID = @SettingsID


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_InkData_Get] to public
go
/***********************************************
* Sproc: cs_InkData_Update
* File Date: 11/29/2006 10:07:31 AM
***********************************************/
Print 'Creating...cs_InkData_Update'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_InkData_Update]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_InkData_Update]
GO

Create Proc [dbo].[cs_InkData_Update]
(	
	@SectionID int,
	@SettingsID int,
	@Ink NTEXT,
	@DateUpdated datetime,
	@InkID int
)
as

update cs_InkData 
SET
	Ink = @Ink, 
	DateUpdated = @DateUpdated
where
	SettingsID = @SettingsID and SectionID = @SectionID and InkID = @InkID






GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_InkData_Update] to public
go
/***********************************************
* Sproc: cs_Licenses_Get
* File Date: 11/29/2006 10:07:31 AM
***********************************************/
Print 'Creating...cs_Licenses_Get'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Licenses_Get]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Licenses_Get]
GO

CREATE PROCEDURE dbo.cs_Licenses_Get AS

SELECT * FROM cs_Licenses
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_Licenses_Get] to public
go
/***********************************************
* Sproc: cs_Licenses_Update
* File Date: 11/29/2006 10:07:31 AM
***********************************************/
Print 'Creating...cs_Licenses_Update'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Licenses_Update]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Licenses_Update]
GO

CREATE PROCEDURE dbo.cs_Licenses_Update
	@LicenseID uniqueidentifier,
	@LicenseType nvarchar(50),
	@LicenseValue ntext
AS

if exists(select LicenseType from cs_Licenses where LicenseType = @LicenseType)
begin
	delete from cs_Licenses where LicenseType = @LicenseType
end

insert into cs_Licenses (LicenseID, LicenseType, LicenseValue) values (@LicenseID, @LicenseType, @LicenseValue)
GO


grant execute on [dbo].[cs_Licenses_Update] to public
go
/***********************************************
* Sproc: cs_LinkCategories_Get
* File Date: 11/29/2006 10:07:30 AM
***********************************************/
Print 'Creating...cs_LinkCategories_Get'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_LinkCategories_Get]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_LinkCategories_Get]
GO



CREATE PROCEDURE dbo.cs_LinkCategories_Get
(
	@SectionID int,
	@SettingsID int,
	@PreLoadLinks bit
)
AS
SET Transaction Isolation Level Read UNCOMMITTED

-- Categories
SELECT  [LinkCategoryID], [SectionID], [Name], [Description], [IsEnabled], [SortOrder], [SettingsID]
FROM cs_LinkCategories
WHERE SectionID = @SectionID and SettingsID = @SettingsID
Order By SortOrder

-- Do we need to return links as well?
IF (@PreLoadLinks = 1)
BEGIN
	SELECT [LinkID], l.[LinkCategoryID], [Title], [Url], l.[IsEnabled], l.[SortOrder], l.[SettingsID], [Rel], l.[Description], [DateCreated]
	FROM cs_Links l inner join cs_LinkCategories c on l.LinkCategoryID = c.LinkCategoryID
	WHERE c.SectionID = @SectionID and c.SettingsID = @SettingsID
	Order By c.SortOrder, l.SortOrder
END


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_LinkCategories_Get] to public
go



/***********************************************
* Sproc: cs_LinkCategory_CreateUpdateDelete
* File Date: 11/29/2006 10:07:32 AM
***********************************************/
Print 'Creating...cs_LinkCategory_CreateUpdateDelete'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_LinkCategory_CreateUpdateDelete]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_LinkCategory_CreateUpdateDelete]
GO

--exec dbo.cs_LinkCategory_CreateUpdateDelete @LinkCategoryID = 3, @DeleteLinkCategory = 1

CREATE PROCEDURE dbo.cs_LinkCategory_CreateUpdateDelete
	@DeleteLinkCategory bit=0,
	@SectionID int,
	@Name nvarchar(256)='',
	@Description nvarchar(2000)=null,
	@IsEnabled bit=1,
	@SortOrder int=0,
	@SettingsID int,
	@LinkCategoryID int=0 out
AS
SET Transaction Isolation Level Read UNCOMMITTED

-- Are we deleting?
if @DeleteLinkCategory = 1
begin
	DELETE FROM cs_Links WHERE LinkCategoryID = @LinkCategoryID and SettingsID = @SettingsID
	DELETE FROM cs_LinkCategories WHERE LinkCategoryID = @LinkCategoryID and SectionID = @SectionID and SettingsID = @SettingsID
	RETURN
end

-- Are we updating?
if @LinkCategoryID > 0
begin
	UPDATE cs_LinkCategories SET
		[Name] = @Name,
		[Description] = @Description,
		IsEnabled = @IsEnabled,
		SortOrder = @SortOrder
	WHERE LinkCategoryID = @LinkCategoryID and SectionID = @SectionID and SettingsID = @SettingsID
end
else
begin
	If( @SortOrder = 0 )
	Begin
		Select @SortOrder = max(SortOrder) + 1 from cs_LinkCategories where SectionID = @SectionID and SettingsID = @SettingsID

		if(@SortOrder is null)
			Select	@SortOrder = 0
	End
	INSERT INTO cs_LinkCategories (SectionID, [Name], [Description], IsEnabled, SortOrder, SettingsID)
		VALUES (@SectionID, @Name, @Description, @IsEnabled, @SortOrder, @SettingsID)
	set @LinkCategoryID = @@IDENTITY
end


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_LinkCategory_CreateUpdateDelete] to public
go
/***********************************************
* Sproc: cs_LinkCategory_UpdateSortOrder
* File Date: 11/29/2006 10:07:32 AM
***********************************************/
Print 'Creating...cs_LinkCategory_UpdateSortOrder'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_LinkCategory_UpdateSortOrder]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_LinkCategory_UpdateSortOrder]
GO



CREATE procedure [dbo].cs_LinkCategory_UpdateSortOrder
( 
            @LinkCategoryID int, 
	    @SettingsID int,
            @MoveUp bit 
) 
AS 
SET Transaction Isolation Level Read UNCOMMITTED
BEGIN 
	set nocount on
	
	DECLARE @currentSortValue int 
	DECLARE @replaceSortValue int 
	DECLARE @replaceLinkCategoryID int
	DECLARE @SectionID int
	
	-- Get the current sort order 
	SELECT @currentSortValue = SortOrder, @SectionID = SectionID FROM cs_LinkCategories WHERE LinkCategoryID = @LinkCategoryID  and SettingsID = @SettingsID
	
	-- Move the item up or down? 
	IF (@MoveUp = 1) 
	BEGIN 
		SELECT @replaceSortValue = coalesce(f.SortOrder, -1), @replaceLinkCategoryID = coalesce(f.LinkCategoryID, -1)
			FROM cs_LinkCategories f
				inner join (
					select top 1 * 
					from cs_LinkCategories 
					WHERE SectionID = @SectionID and SortOrder < @currentSortValue  and SettingsID = @SettingsID order by SortOrder DESC
				) as pf on 
					pf.LinkCategoryID = f.LinkCategoryID  and f.SettingsID = @SettingsID

		if( @replaceSortValue != -1 And @replaceSortValue is Not Null  )
		begin	
			UPDATE cs_LinkCategories SET SortOrder = @currentSortValue WHERE LinkCategoryID = @replaceLinkCategoryID  and SettingsID = @SettingsID
			UPDATE cs_LinkCategories SET SortOrder = @replaceSortValue WHERE LinkCategoryID = @LinkCategoryID  and SettingsID = @SettingsID
		END 
	END 
	ELSE 
	BEGIN 
		SELECT @replaceSortValue = coalesce(f.SortOrder, -1), @replaceLinkCategoryID = coalesce(f.LinkCategoryID, -1)
			FROM cs_LinkCategories f
				inner join (
					select top 1 * 
					FROM cs_LinkCategories 
					WHERE SectionID = @SectionID and SortOrder > @currentSortValue  and SettingsID = @SettingsID order by SortOrder ASC				
				) as pf on 
					pf.LinkCategoryID = f.LinkCategoryID  and f.SettingsID = @SettingsID


		if( @replaceSortValue != -1 And @replaceSortValue is Not Null  )
		begin		
			UPDATE cs_LinkCategories SET SortOrder = @currentSortValue WHERE LinkCategoryID = @replaceLinkCategoryID  and SettingsID = @SettingsID
			UPDATE cs_LinkCategories SET SortOrder = @replaceSortValue WHERE LinkCategoryID = @LinkCategoryID  and SettingsID = @SettingsID
		end
	END 
END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_LinkCategory_UpdateSortOrder] to public
go
/***********************************************
* Sproc: cs_Links_Get
* File Date: 11/29/2006 10:07:31 AM
***********************************************/
Print 'Creating...cs_Links_Get'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Links_Get]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Links_Get]
GO



CREATE PROCEDURE dbo.cs_Links_Get
	@LinkCategoryID int,
	@SettingsID int
AS
SET Transaction Isolation Level Read UNCOMMITTED

	SELECT [LinkID], [LinkCategoryID], [Title], [Url], [IsEnabled], [SortOrder], [SettingsID], [Rel], [Description], [DateCreated]
	FROM cs_Links
	WHERE LinkCategoryID = @LinkCategoryID and SettingsID = @SettingsID
	Order By SortOrder

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_Links_Get] to public
go


/***********************************************
* Sproc: cs_Link_CreateUpdateDelete
* File Date: 11/29/2006 10:07:30 AM
***********************************************/
Print 'Creating...cs_Link_CreateUpdateDelete'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Link_CreateUpdateDelete]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Link_CreateUpdateDelete]
GO

CREATE PROCEDURE dbo.cs_Link_CreateUpdateDelete
	@DeleteLink bit=0,
	@LinkCategoryID int=0,
	@Title nvarchar(100)='',
	@Url nvarchar(255)='',
	@Rel nvarchar(100)='',
	@Description nvarchar(2000)='',
	@IsEnabled bit=1,
	@SortOrder int=0,
	@SettingsID int,
	@LinkID int=0 out
AS
SET Transaction Isolation Level Read UNCOMMITTED
-- Are we deleting?
if @DeleteLink = 1
begin
	DELETE FROM cs_Links WHERE LinkID = @LinkID
end

-- Are we updating?
if @LinkID > 0
begin
	UPDATE cs_Links SET
		Title = @Title,
		Url = @Url,
		Rel = @Rel,
		[Description] = @Description,
		IsEnabled = @IsEnabled,
		SortOrder = @SortOrder
	WHERE LinkID = @LinkID and LinkCategoryID = @LinkCategoryID and SettingsID = @SettingsID
end
else
begin
	If( @SortOrder = 0 )
	Begin
		Select @SortOrder = max(SortOrder) + 1 from cs_Links where LinkCategoryID = @LinkCategoryID and SettingsID = @SettingsID

		if(@SortOrder is null)
			Select @SortOrder = 0
	End
	INSERT INTO cs_Links (LinkCategoryID, Title, Url, Rel, [Description], IsEnabled, SortOrder, SettingsID)
		VALUES (@LinkCategoryID, @Title, @Url, @Rel, @Description, @IsEnabled, @SortOrder, @SettingsID)
	set @LinkID = @@IDENTITY
end

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO


grant execute on [dbo].[cs_Link_CreateUpdateDelete] to public
go
/***********************************************
* Sproc: cs_Link_UpdateSortOrder
* File Date: 11/29/2006 10:07:31 AM
***********************************************/
Print 'Creating...cs_Link_UpdateSortOrder'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Link_UpdateSortOrder]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Link_UpdateSortOrder]
GO



CREATE procedure [dbo].cs_Link_UpdateSortOrder
( 
            @LinkID int,
	    @SettingsID int, 
            @MoveUp bit 
) 
AS 
SET Transaction Isolation Level Read UNCOMMITTED
BEGIN 
	set nocount on
	
	DECLARE @currentSortValue int 
	DECLARE @replaceSortValue int 
	DECLARE @replaceLinkID int
	DECLARE @LinkCategoryID int
	
	-- Get the current sort order 
	SELECT @currentSortValue = SortOrder, @LinkCategoryID = LinkCategoryID FROM cs_Links WHERE LinkID = @LinkID  and SettingsID = @SettingsID

	-- Move the item up or down? 
	IF (@MoveUp = 1) 
	BEGIN 
		SELECT @replaceSortValue = coalesce(f.SortOrder, -1), @replaceLinkID = coalesce(f.LinkID, -1)
			FROM cs_Links f
				inner join (
					select top 1 * 
					from cs_Links 
					WHERE LinkCategoryID = @LinkCategoryID and SortOrder < @currentSortValue and SettingsID = @SettingsID order by SortOrder DESC
				) as pf on 
					pf.LinkID = f.LinkID and f.SettingsID = @SettingsID
		if( @replaceSortValue != -1 And @replaceSortValue is Not Null )
		begin	
			UPDATE cs_Links SET SortOrder = @currentSortValue WHERE LinkID = @replaceLinkID and SettingsID = @SettingsID
			UPDATE cs_Links SET SortOrder = @replaceSortValue WHERE LinkID = @LinkID and SettingsID = @SettingsID
		END 
	END 
	ELSE 
	BEGIN 
		SELECT @replaceSortValue = coalesce(f.SortOrder, -1), @replaceLinkID = coalesce(f.LinkID, -1)
			FROM cs_Links f
				inner join (
					select top 1 * 
					FROM cs_Links 
					WHERE LinkCategoryID = @LinkCategoryID and SortOrder > @currentSortValue and SettingsID = @SettingsID order by SortOrder ASC				
				) as pf on 
					pf.LinkID = f.LinkID and f.SettingsID = @SettingsID


		if( @replaceSortValue != -1 And @replaceSortValue is Not Null )
		begin		
			UPDATE cs_Links SET SortOrder = @currentSortValue WHERE LinkID = @replaceLinkID and SettingsID = @SettingsID
			UPDATE cs_Links SET SortOrder = @replaceSortValue WHERE LinkID = @LinkID and SettingsID = @SettingsID
		end
	END 
END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_Link_UpdateSortOrder] to public
go
/***********************************************
* Sproc: cs_MarkPostAsRead
* File Date: 11/29/2006 10:07:30 AM
***********************************************/
Print 'Creating...cs_MarkPostAsRead'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_MarkPostAsRead]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_MarkPostAsRead]
GO

CREATE         PROCEDURE [dbo].cs_MarkPostAsRead
(
	@PostID	int,
	@UserName nvarchar (50),
	@SettingsID int
)
 AS
SET Transaction Isolation Level Read UNCOMMITTED
BEGIN

	-- If @UserName is null it is an anonymous user
	IF @UserName IS NOT NULL
	BEGIN
		DECLARE @SectionID int
		DECLARE @PostDate datetime

		-- Mark the post as read
		-- *********************

		-- Only for PostLevel = 1
		IF EXISTS (SELECT PostID FROM cs_Posts WHERE PostID = @PostID AND PostLevel = 1 and SettingsID = @SettingsID)
			IF NOT EXISTS (SELECT HasRead FROM PostsReadx WHERE UserName = @UserName and PostID = @PostID and SettingsID = @SettingsID)
				INSERT INTO PostsRead (UserName, PostID, SettingsID) VALUES (@UserName, @PostID, @SettingsID)

	END

END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_MarkPostAsRead] to public
go
/***********************************************
* Sproc: cs_Message_CreateUpdateDelete
* File Date: 11/29/2006 10:07:32 AM
***********************************************/
Print 'Creating...cs_Message_CreateUpdateDelete'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Message_CreateUpdateDelete]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Message_CreateUpdateDelete]
GO

create procedure [dbo].cs_Message_CreateUpdateDelete
(
	@MessageID int,
	@Title NVarChar(1024),
	@Body NVarChar(4000),
	@Action int,
	@SettingsID int
)
AS
SET Transaction Isolation Level Read UNCOMMITTED
-- CREATE
IF @Action = 0
BEGIN
	SELECT 'Not Implemented'
END
-- UPDATE
ELSE IF @Action  = 1
BEGIN
	UPDATE
		cs_Messages
	SET
		Title = @Title,
		Body = @Body
	WHERE
		MessageID = @MessageID and SettingsID = @SettingsID
END

-- DELETE
ELSE IF @Action = 2
BEGIN
	SELECT 'Not Implemented'
END	


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].cs_Message_CreateUpdateDelete to public
go
/***********************************************
* Sproc: cs_Moderate_ApprovePost
* File Date: 11/29/2006 10:07:31 AM
***********************************************/
Print 'Creating...cs_Moderate_ApprovePost'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Moderate_ApprovePost]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Moderate_ApprovePost]
GO


CREATE         procedure [dbo].cs_Moderate_ApprovePost
(
	@PostID		int,
	@ApprovedBy	int,
	@SettingsID 	int
)
AS
SET Transaction Isolation Level Read UNCOMMITTED
DECLARE @SectionID 	int
DECLARE @ThreadID 	int
DECLARE @PostLevel 	int
DECLARE @UserID		int
DECLARE @IsLocked	bit

-- first make sure that the post is ALREADY non-approved
IF (SELECT IsApproved FROM cs_Posts (nolock) WHERE PostID = @PostID and SettingsID = @SettingsID) = 1
BEGIN
	print 'Post is already approved'
	SELECT 0
	RETURN
END
ELSE
BEGIN

	print 'Post is not approved'

	-- Get details about the thread and forum this post belongs in
	SELECT
		@SectionID = SectionID,
		@ThreadID = ThreadID,
		@PostLevel = PostLevel,
		@UserID	= UserID,
		@IsLocked = IsLocked
	FROM
		cs_Posts
	WHERE
		PostID = @PostID and SettingsID = @SettingsID

	-- Approve the post
	UPDATE 
		cs_Posts
	SET 
		IsApproved = 1
	WHERE 
		PostID = @PostID and SettingsID = @SettingsID

	-- Approved the thread if necessary
	IF @PostLevel = 1
		UPDATE
			cs_Threads
		SET
			IsApproved = 1
		WHERE
			ThreadID = @ThreadID and SettingsID = @SettingsID

	-- Update the user's post count
	exec cs_system_UpdateUserPostCount @SectionID, @UserID, @SettingsID

	-- Update the forum statistics
	exec cs_system_UpdateForum @SectionID, @ThreadID, @PostID, @SettingsID

	-- Clean up unnecessary columns in forumsread
	exec cs_system_CleanForumsRead @SectionID, @SettingsID

	-- update the thread stats
	exec cs_system_UpdateThread @ThreadID, @PostID, @SettingsID

	-- Update Moderation audit table
	-- Update the ModerationAudit table
	exec cs_system_ModerationAction_AuditEntry 1, @ApprovedBy, @PostID, null, @SectionID, @SettingsID, null

	-- Send back a success code
	SELECT 1
	
END


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_Moderate_ApprovePost] to public
go
/***********************************************
* Sproc: cs_Moderate_CheckUser
* File Date: 11/29/2006 10:07:33 AM
***********************************************/
Print 'Creating...cs_Moderate_CheckUser'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Moderate_CheckUser]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Moderate_CheckUser]
GO

CREATE procedure [dbo].cs_Moderate_CheckUser 
(
	@UserID		int,
	@SectionID	int,
	@SettingsID 	int
)
AS
SET Transaction Isolation Level Read UNCOMMITTED

IF EXISTS(SELECT SectionID FROM cs_Moderators WHERE UserID = @UserID AND SectionID = 0 and SettingsID = @SettingsID)
  SELECT 1
ELSE
  IF EXISTS (SELECT SectionID FROM cs_Moderators WHERE UserID = @UserID AND SectionID = @SectionID AND SettingsID = @SettingsID)
    SELECT 1
  ELSE
    SELECT 0



GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_Moderate_CheckUser] to public
go
/***********************************************
* Sproc: cs_Moderate_DeletePost
* File Date: 11/29/2006 10:07:32 AM
***********************************************/
Print 'Creating...cs_Moderate_DeletePost'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Moderate_DeletePost]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Moderate_DeletePost]
GO

CREATE PROCEDURE [dbo].cs_Moderate_DeletePost
(
	@PostID INT,
	@DeletedBy INT,
	@Reason NVARCHAR(1024) = '',
	@DeleteChildPosts BIT = 1,
	@SettingsID int
)
AS
-- Deletes the post

SET Transaction Isolation Level Read UNCOMMITTED

DECLARE @IsApproved bit
DECLARE @SectionID int

-- First, get information about the post that is about to be deleted.
SELECT
    @IsApproved = IsApproved,
    @SectionID = SectionID
FROM
    cs_Posts
WHERE
    PostID = @PostID and SettingsID = @SettingsID

-- If the post is not approved, permanently delete the post
IF (@IsApproved = 0)
BEGIN	
    	-- Delete the post.
	DELETE FROM cs_Posts WHERE PostID = @PostID AND SettingsID = @SettingsID

	-- Update moderation statistics
	UPDATE	cs_Sections
	SET		PostsToModerate = (SELECT Count(PostID) FROM cs_Posts WHERE SectionID = @SectionID AND IsApproved = 0 and SettingsID = @SettingsID)
	WHERE	SectionID = @SectionID AND SettingsID = @SettingsID

	-- Update Moderation Audit table
	IF (@Reason IS NULL OR @Reason = '')
		SET @Reason = 'Automatic generated reason: the post has been deleted on request.'

	EXEC cs_system_ModerationAction_AuditEntry 4, @DeletedBy, @PostID, null, null, @SettingsID, @Reason
END	
ELSE
BEGIN
	DECLARE @DeletedSectionID INT
	DECLARE @OldThreadID INT
	DECLARE @NewThreadID INT
	
	-- Init data	
	SELECT @DeletedSectionID = SectionID FROM cs_Sections WHERE SettingsID = @SettingsID and ForumType = 50
	SELECT @OldThreadID = ThreadID, @SectionID = SectionID FROM cs_Posts WHERE SettingsID = @SettingsID AND PostID = @PostID
	SET @NewThreadID = NULL
	
	-- Is this a private message post (@SectionID = 0)?
	IF (@SectionID = 0)
	BEGIN
		-- Permanently delete the post and its replies
		EXEC cs_Post_Delete @SectionID, @SettingsID, @PostID, 0, @DeletedBy, @Reason

		-- Statistics update
		EXEC cs_system_ResetThreadStatistics @OldThreadID
	END
	ELSE -- (@SectionID <> 0)
	BEGIN
		IF (@DeleteChildPosts = 1)
			-- Move the post and its replies to 'Deleted Posts' forum
			EXEC cs_system_DeletePostAndChildren @PostID, @DeleteChildPosts, @SettingsID, @DeletedBy, @Reason, @NewThreadID OUT, NULL

		ELSE -- (@DeleteChildPosts <> 1)
			-- Move the post to 'Deleted Posts' forum, reassign children to deleted post's parent
			EXEC cs_system_DeletePostAndAdoptChildren @PostID, @SettingsID, @DeletedBy, @Reason, @NewThreadID OUTPUT

		-- Statistics update
		EXEC cs_system_ResetThreadStatistics @OldThreadID
		EXEC cs_system_ResetThreadStatistics @NewThreadID
		EXEC cs_system_ResetForumStatistics @SectionID
		EXEC cs_system_ResetForumStatistics @DeletedSectionID
	END
END

GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO


grant execute on [dbo].[cs_Moderate_DeletePost] to public
go
/***********************************************
* Sproc: cs_Moderate_Forums
* File Date: 11/29/2006 10:07:31 AM
***********************************************/
Print 'Creating...cs_Moderate_Forums'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Moderate_Forums]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Moderate_Forums]
GO

CREATE procedure [dbo].cs_Moderate_Forums
	(
		@SettingsID	int,
		@UserID int,	
		@ApplicationType smallint = 0
	)
	AS
	SET Transaction Isolation Level Read UNCOMMITTED
	BEGIN
	
SELECT
	LastUserActivity = '1/1/1797',
	F.SectionID, F.SettingsID, F.IsActive, F.ParentID, F.GroupID, F.Name, F.NewsgroupName, F.Description, F.DateCreated, F.Url, F.IsModerated,
	F.DaysToView, F.SortOrder, F.TotalPosts, F.TotalThreads, F.DisplayMask, F.EnablePostStatistics, F.EnablePostPoints, F.EnableAutoDelete, F.EnableAnonymousPosting,
	F.AutoDeleteThreshold, F.MostRecentPostID, F.MostRecentThreadID, F.MostRecentThreadReplies, F.MostRecentPostSubject, F.MostRecentPostAuthor,
	F.MostRecentPostAuthorID, F.MostRecentPostDate, F.PostsToModerate, F.ForumType, F.IsSearchable, F.ApplicationType, F.ApplicationKey, F.Path,
	F.PropertyNames as SectionPropertyNames, F.PropertyValues as SectionPropertyValues, F.DefaultLanguage
FROM
	cs_Sections F
WHERE
	F.IsActive = 1 AND F.SettingsID = @SettingsID AND F.ApplicationType = @ApplicationType

	END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_Moderate_Forums] to public
go
/***********************************************
* Sproc: cs_Moderate_Forum_Roles
* File Date: 11/29/2006 10:07:33 AM
***********************************************/
Print 'Creating...cs_Moderate_Forum_Roles'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Moderate_Forum_Roles]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Moderate_Forum_Roles]
GO




create procedure [dbo].cs_Moderate_Forum_Roles
(
	@SectionID	int,
	@SettingsID int
)
AS
SET Transaction Isolation Level Read UNCOMMITTED
SELECT 
	R.RoleID,
	R.RoleName as [Name],
	Description 
FROM 
	cs_SectionPermissions P,
	aspnet_roles R
WHERE
	P.RoleID = R.RoleID AND
	P.allowmask & convert(bigint,0x0000100000000000) = convert(bigint,0x0000100000000000)  AND
	SectionID = @SectionID and P.SettingsID = @SettingsID







GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].cs_Moderate_Forum_Roles to public
go
/***********************************************
* Sproc: cs_Moderate_Post_Move
* File Date: 11/29/2006 10:07:33 AM
***********************************************/
Print 'Creating...cs_Moderate_Post_Move'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Moderate_Post_Move]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Moderate_Post_Move]
GO



CREATE    PROCEDURE [dbo].cs_Moderate_Post_Move
(
    @PostID int,
    @MoveToSectionID int,
    @MovedBy int,
    @SettingsID int
)
AS
SET Transaction Isolation Level Read UNCOMMITTED
DECLARE @ThreadID INT
DECLARE @SectionID INT
DECLARE @IsApproved BIT
DECLARE @PostLevel INT
DECLARE @Notes NVARCHAR(1024)

-- First, get information about the post that is about to be moved.
SELECT
	@ThreadID = ThreadID,
	@SectionID = SectionID,
	@PostLevel = PostLevel,
	@IsApproved = IsApproved
FROM
	cs_Posts
WHERE
	PostID = @PostID and SettingsID = @SettingsID

-- EAD: We only move the post if it is a top level post.
IF @PostLevel = 1
BEGIN
	DECLARE @MoveToIsModerated SMALLINT
	
	-- Get information about the destination forum.
	SELECT 
		@MoveToIsModerated = IsModerated
	FROM 
		cs_Sections
	WHERE 
		SectionID = @MoveToSectionID and SettingsID = @SettingsID
	
	-- If the post is not already approved, check the moderation status and permissions on the moderator for approved status.
	IF @IsApproved = 0
	BEGIN
		-- If the destination forum requires moderation, make sure the moderator has permission.
		IF @MoveToIsModerated = 1
		BEGIN
			IF EXISTS(
				SELECT
					A.UserId
				FROM
					aspnet_UsersInRoles A, cs_UserProfile U
				WHERE
					U.MembershipID = A.UserId and
					U.UserID = @MovedBy  and U.SettingsID = @SettingsID
					AND A.RoleId IN (
						SELECT 
							RoleID 
						FROM 
							cs_SectionPermissions
						WHERE 
							SectionID = @SectionID
							AND AllowMask & convert(bigint,0x0000100000000000) = convert(bigint,0x0000100000000000)  and SettingsID = @SettingsID
					)
			)
			BEGIN
				-- The moderator has permissions to move the post and approve it.		
				UPDATE
					cs_Posts
				SET 
					SectionID = @MoveToSectionID
				WHERE 
					ThreadID = @ThreadID and SettingsID = @SettingsID

				UPDATE
					cs_PostAttachments
				SET
					SectionID = @MoveToSectionID
				WHERE
					PostID IN (SELECT PostID FROM cs_Posts WHERE ThreadID = @ThreadID AND SettingsID = @SettingsID)

				UPDATE
					cs_Threads
				SET 
					SectionID = @MoveToSectionID
				WHERE 
					ThreadID = @ThreadID and SettingsID = @SettingsID

				-- approve the post
				EXEC cs_Moderate_ApprovePost @PostID, @MovedBy, @SettingsID
				
				SET @Notes = 'The post was moved and approved.'
				PRINT @Notes
				SELECT 2
			END
			ELSE BEGIN
				-- The moderator has permissions to move the post but not approve.			
				UPDATE
					cs_Posts
				SET 
					SectionID = @MoveToSectionID
				WHERE 
					ThreadID = @ThreadID and SettingsID = @SettingsID

				UPDATE
					cs_PostAttachments
				SET
					SectionID = @MoveToSectionID
				WHERE
					PostID IN (SELECT PostID FROM cs_Posts WHERE ThreadID = @ThreadID AND SettingsID = @SettingsID)

				UPDATE
					cs_Threads
				SET 
					SectionID = @MoveToSectionID
				WHERE 
					ThreadID = @ThreadID and SettingsID = @SettingsID
				
				SET @Notes = 'The post was moved but not approved.'
				PRINT @Notes
				SELECT 1
			END
		END
		ELSE BEGIN
			UPDATE
				cs_Posts
			SET 
				SectionID = @MoveToSectionID
			WHERE 
				ThreadID = @ThreadID and SettingsID = @SettingsID

			UPDATE
				cs_PostAttachments
			SET
				SectionID = @MoveToSectionID
			WHERE
				PostID IN (SELECT PostID FROM cs_Posts WHERE ThreadID = @ThreadID AND SettingsID = @SettingsID)

			UPDATE
				cs_Threads
			SET 
				SectionID = @MoveToSectionID
			WHERE 
				ThreadID = @ThreadID and SettingsID = @SettingsID

			-- The destination forum is not moderated, approve the post and move the post.
			EXEC cs_Moderate_ApprovePost @PostID, @MovedBy, @SettingsID
			
			SET @Notes = 'The post was moved and approved.'
			PRINT @Notes
			SELECT 2
		END
	END
	ELSE BEGIN
		-- The post is already approved, move the post.
		UPDATE
			cs_Posts
		SET 
			SectionID = @MoveToSectionID
		WHERE 
			ThreadID = @ThreadID and SettingsID = @SettingsID

		UPDATE
			cs_PostAttachments
		SET
			SectionID = @MoveToSectionID
		WHERE
			PostID IN (SELECT PostID FROM cs_Posts WHERE ThreadID = @ThreadID AND SettingsID = @SettingsID)

		UPDATE
			cs_Threads
		SET 
			SectionID = @MoveToSectionID
		WHERE 
			ThreadID = @ThreadID and SettingsID = @SettingsID
		
		print 'The approved post was moved.'
		SET @Notes = 'The approved post was moved.'
		SELECT 3
	
	END

	-- Reset the statistics on both forums.
	EXEC cs_system_ResetForumStatistics @SectionID
	EXEC cs_system_ResetForumStatistics @MoveToSectionID
	
	-- Reset the thread statistics on the moved thread.
	EXEC cs_system_ResetThreadStatistics @ThreadID
		
	-- Update Moderation Audit table
	EXEC cs_system_ModerationAction_AuditEntry 3, @MovedBy, @PostID, null, @SectionID, @SettingsID, @Notes

END
ELSE BEGIN
	print 'The post was not moved.'
	SELECT 0
END



GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_Moderate_Post_Move] to public
go
/***********************************************
* Sproc: cs_Moderate_Post_UpdateParent
* File Date: 11/29/2006 10:07:31 AM
***********************************************/
Print 'Creating...cs_Moderate_Post_UpdateParent'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Moderate_Post_UpdateParent]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Moderate_Post_UpdateParent]
GO

CREATE    PROCEDURE [dbo].cs_Moderate_Post_UpdateParent
(
	@PostID int,
	@ParentID int,
	@MovedBy int,
	@SettingsID int
)
AS

SET Transaction Isolation Level Read UNCOMMITTED

DECLARE @ThreadID int

SELECT @ThreadID = ThreadID
FROM cs_Posts
WHERE PostID = @PostID
	 and SettingsID = @SettingsID

-- ensure the posts are in the same thread and that the post being moved is not the first post
IF @ThreadID is null 
	OR @ThreadID <> (SELECT ThreadID FROM cs_Posts WHERE PostID = @PostID and SettingsID = @SettingsID)
	OR @PostID = (SELECT PostID FROM cs_Posts WHERE ThreadID = @ThreadID and SettingsID = @SettingsID and PostLevel = 0)
	RETURN

BEGIN TRAN

-- Do the Update
UPDATE
	cs_Posts
SET
	ParentID = @ParentID
WHERE
	PostID = @PostID and SettingsID = @SettingsID

-- Update thread statistics
EXEC cs_system_UpdateThread @ThreadID, 0, @SettingsID

-- Update moderation actions
EXEC cs_system_ModerationAction_AuditEntry 3, @MovedBy, @PostID, null, null, @SettingsID, null

COMMIT TRAN


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_Moderate_Post_UpdateParent] to public
go
/***********************************************
* Sproc: cs_Moderate_Thread_Merge
* File Date: 11/29/2006 10:07:31 AM
***********************************************/
Print 'Creating...cs_Moderate_Thread_Merge'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Moderate_Thread_Merge]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Moderate_Thread_Merge]
GO


CREATE    PROCEDURE [dbo].cs_Moderate_Thread_Merge
(
	@ParentThreadID int,
	@ChildThreadID int,
	@JoinBy int,
	@SettingsID int
)
AS
SET Transaction Isolation Level Read UNCOMMITTED
DECLARE @ParentSectionID int
DECLARE @LastPostInParent int
DECLARE @PostLevelInParent int
DECLARE @SortOrderInParent int
DECLARE @ChildSectionID int
DECLARE @FirstPostInChild int
DECLARE @PostLevelInChild int
DECLARE @SortOrderInChild int
DECLARE @LastPostInChild int

-- Check to ensure we can perform this opertation
IF ((SELECT ThreadID FROM cs_Threads WHERE ThreadID = @ChildThreadID and SettingsID = @SettingsID) = @ParentThreadID)
	RETURN

-- Get details on the parent thread
SELECT TOP 1
	@ParentSectionID = SectionID,
	@LastPostInParent = PostID,
	@PostLevelInParent = PostLevel,
	@SortOrderInParent = SortOrder
FROM
	cs_Posts
WHERE
	ThreadID = @ParentThreadID and SettingsID = @SettingsID
ORDER BY
	SortOrder DESC

-- Get details on the child thread
SELECT TOP 1
	@ChildSectionID = SectionID,
	@FirstPostInChild = PostID,
	@PostLevelInChild = PostLevel,
	@SortOrderInChild = SortOrder
FROM
	cs_Posts
WHERE
	ThreadID = @ChildThreadID and SettingsID = @SettingsID

-- don't know why this is here
-- Get the last post in the child thread
--SELECT 
--	@LastPostInChild = MostRecentPostID
--FROM
--	cs_Threads
--WHERE
--	ThreadID = @ChildThreadID

BEGIN TRAN

-- this is now done in the cs_system_UpdateThread sproc
-- Update the PostLevel and SortOrder for the Child posts before merging
--UPDATE 
--	cs_Posts
--SET
--	PostLevel = PostLevel + @PostLevelInParent
--WHERE
--	ThreadID = @ChildThreadID
--
--UPDATE 
--	cs_Posts
--SET
--	SortOrder = SortOrder + @SortOrderInParent
--WHERE
--	ThreadID = @ChildThreadID

-- Approve the post
UPDATE
	cs_Posts
SET
	IsApproved = 1
WHERE
	PostID = @FirstPostInChild AND SettingsID = @SettingsID

-- Do the Updates
UPDATE
	cs_PostAttachments
SET
	SectionID = @ParentSectionID
WHERE
	PostID IN (SELECT PostID FROM cs_Posts WHERE ThreadID = @ChildThreadID AND SettingsID = @SettingsID)

UPDATE
	cs_Posts
SET
	ThreadID = @ParentThreadID,
	SectionID = @ParentSectionID,
	PostLevel = PostLevel + @PostLevelInParent,
	SortOrder = SortOrder + @SortOrderInParent,
	ParentID = @LastPostInParent
WHERE
	ThreadID = @ChildThreadID and SettingsID = @SettingsID

-- Now delete all of the old thread info
DELETE FROM 
	cs_SearchBarrel
WHERE 
	ThreadID = @ChildThreadID and SettingsID = @SettingsID

-- Delete all thread tracking data.	
DELETE FROM 
	cs_TrackedThreads
WHERE 
	ThreadID = @ChildThreadID and SettingsID = @SettingsID

-- Cleanup ThreadsRead
DELETE
	cs_ThreadsRead
WHERE
	ThreadID = @ChildThreadID  and SettingsID = @SettingsID

-- Delete the child thread
DELETE 
	cs_Threads
WHERE
	ThreadID = @ChildThreadID and SettingsID = @SettingsID

-- Update thread statistics
EXEC cs_system_UpdateThread @ParentThreadID, 0, @SettingsID

-- Update forum statistics
EXEC cs_system_UpdateForum @ParentSectionID, @ParentThreadID, @LastPostInParent, @SettingsID
EXEC cs_system_ResetForumStatistics @ChildSectionID

-- Update moderation actions
EXEC cs_system_ModerationAction_AuditEntry 7, @JoinBy, @ChildThreadID, null, null, @SettingsID, null

COMMIT TRAN



GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_Moderate_Thread_Merge] to public
go
/***********************************************
* Sproc: cs_Moderate_Thread_Split
* File Date: 11/29/2006 10:07:31 AM
***********************************************/
Print 'Creating...cs_Moderate_Thread_Split'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Moderate_Thread_Split]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Moderate_Thread_Split]
GO



CREATE       PROCEDURE [dbo].cs_Moderate_Thread_Split
(
	@PostID INT,
	@MoveToForum INT,
	@SplitBy INT,
	@SettingsID int
)
AS

SET Transaction Isolation Level Read UNCOMMITTED
DECLARE @IsSticky BIT
DECLARE @StickyDate DATETIME
DECLARE @IsLocked BIT
DECLARE @NewThreadID INT
DECLARE @OldThreadID INT
DECLARE @UserID INT
DECLARE @PostAuthor NVARCHAR(64)
DECLARE @PostDate DATETIME
DECLARE @EmoticonID INT
DECLARE @TopPostLevel INT
DECLARE @TopSortOrder INT
DECLARE @TotalReplies INT
DECLARE	@MostRecentPostAuthor NVARCHAR(64)
DECLARE	@MostRecentPostAuthorID INT
DECLARE	@MostRecentPostID INT

-- Get details on the post
SELECT 
	@PostDate = PostDate,
	@UserID = UserID,
	@PostAuthor = PostAuthor,
	@IsSticky = 0,			-- shouldn't be a stickie when splitting
	@IsLocked = IsLocked,
	@StickyDate = GetDate(),
	@EmoticonID = EmoticonID,
	@OldThreadID = ThreadID		-- to delete later if no more replies
FROM 
	cs_Posts 
WHERE 
	PostID = @PostID and SettingsID = @SettingsID

BEGIN TRAN

-- Create a new thread by inserting
INSERT cs_Threads 	
	( SectionID,
	PostDate, 
	UserID, 
	PostAuthor, 
	ThreadDate, 
	MostRecentPostAuthor, 
	MostRecentPostAuthorID, 	
	MostRecentPostID, 
	IsLocked, 
	IsApproved,
	IsSticky, 
	StickyDate, 
	ThreadEmoticonID,
	SettingsID )
VALUES
	( @MoveToForum, 	-- the forum we are moving to
	@PostDate, 
	@UserID, 
	@PostAuthor,
	@PostDate,
	@PostAuthor,	-- Dummy data until we move all posts below
	@UserID, 	-- Dummy data until we move all posts below
	0,		-- MostRecentPostID, which we don't know yet.
	@IsLocked,
	1,		-- Wouldn't be shown in the forum unless it wasn't approved already.
	@IsSticky,
	@StickyDate,
	@EmoticonID,
	@SettingsID )

SELECT 
	@NewThreadID = @@IDENTITY
FROM
	cs_Threads


-- Update post
UPDATE	cs_Posts
SET		PostLevel = 1,	-- this is now a thread starter
		IsApproved = 1	-- by splitting, if it wasn't approved, it is now
WHERE	PostID = @PostID AND SettingsID = @SettingsID

UPDATE
	cs_PostAttachments
SET
	SectionID = @MoveToForum
WHERE
	PostID IN (SELECT PostID FROM cs_Posts WHERE ThreadID = @OldThreadID AND (PostID = @PostID OR ParentID = @PostID) AND SettingsID = @SettingsID)

-- Update the post and it's childred (if any) with the new threadid
UPDATE 
	cs_Posts 
SET 
	ThreadID = @NewThreadID,
	SectionID = @MoveToForum,
	ParentID = @PostID	-- the toplevel post should now reference itself.
--	PostDate = GetDate()	-- We're not going to reset the DATETIME for the posts
WHERE
	ThreadID = @OldThreadID
	AND (PostID = @PostID OR ParentID = @PostID)  and SettingsID = @SettingsID

-- this is now controlled in the cs_system_UpdateThread sproc
-- Fix the PostLevel and SortOrder details of the new thread
--SELECT 
--	@TopPostLevel = PostLevel,
--	@TopSortOrder = SortOrder
--FROM 
--	cs_Posts 
--WHERE 
--	PostID = @PostID
--
--UPDATE 
--	cs_Posts 
--SET 
---	PostLevel = (PostLevel - @TopPostLevel) + 1,
--	SortOrder = (SortOrder - @TopSortOrder) + 1
--WHERE
--	ThreadID = @NewThreadID

-- Update the threads...
EXEC cs_system_UpdateThread @NewThreadID, 0, @SettingsID
EXEC cs_system_UpdateThread @OldThreadID, 0, @SettingsID

-- Update forum statistics
EXEC cs_system_UpdateForum @MoveToForum, @NewThreadID, @PostID, @SettingsID

-- #7. Update moderation actions
EXEC cs_system_ModerationAction_AuditEntry 8, @SplitBy, @PostID, null, null, @SettingsID, null


COMMIT TRAN



GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_Moderate_Thread_Split] to public
go
/***********************************************
* Sproc: cs_ModerationAudit_Message_Get
* File Date: 11/29/2006 10:07:30 AM
***********************************************/
Print 'Creating...cs_ModerationAudit_Message_Get'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_ModerationAudit_Message_Get]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_ModerationAudit_Message_Get]
GO

CREATE PROCEDURE [dbo].cs_ModerationAudit_Message_Get
(
	@PostID int,
	@PageIndex int,
	@PageSize int,
	@ReturnRecordCount bit,
	@SettingsID int
)
AS
SET Transaction Isolation Level Read UNCOMMITTED

DECLARE @PageLowerBound int
DECLARE @PageUpperBound int

-- First set the rowcount
DECLARE @RowsToReturn int
SET @RowsToReturn = @PageSize * (@PageIndex + 1)
SET ROWCOUNT @RowsToReturn

-- Set the page bounds
SET @PageLowerBound = @PageSize * @PageIndex
SET @PageUpperBound = @PageLowerBound + @PageSize + 1

-- Create a temp table to store the select results
CREATE TABLE #TmpPageIndex 
(
	IndexID int IDENTITY (1, 1) NOT NULL,
	ID int
)

CREATE INDEX page_index ON #TmpPageIndex(IndexID)

-- Select records
INSERT INTO #TmpPageIndex (ID)
	SELECT ID FROM cs_ModerationAudit (nolock) 
	WHERE PostID = @PostID AND SettingsID = @SettingsID 
	ORDER BY ModeratedOn ASC

SELECT
	MA.*,
	U.UserName AS ModeratorName
FROM 
	cs_ModerationAudit MA (nolock) LEFT JOIN cs_vw_Users_FullUser U ON U.cs_UserID = MA.ModeratorID,
	#TmpPageIndex 
WHERE 
	MA.ID = #TmpPageIndex.ID AND
	#TmpPageIndex.IndexID > @PageLowerBound AND
	#TmpPageIndex.IndexID < @PageUpperBound AND 
	MA.SettingsID = @SettingsID
ORDER BY
	IndexID

IF @ReturnRecordCount = 1
	SELECT count(PostID) FROM cs_ModerationAudit (nolock) WHERE PostID = @PostID AND SettingsID = @SettingsID
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].cs_ModerationAudit_Message_Get to public
go

/***********************************************
* Sproc: cs_ModerationAudit_Summary_Get
* File Date: 11/29/2006 10:07:34 AM
***********************************************/
Print 'Creating...cs_ModerationAudit_Summary_Get'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_ModerationAudit_Summary_Get]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_ModerationAudit_Summary_Get]
GO

CREATE PROCEDURE [dbo].cs_ModerationAudit_Summary_Get 
(
	@PostID int = null,
	@UserID int = null,
	@SettingsID int
)
AS
SET Transaction Isolation Level Read UNCOMMITTED
IF (@PostID != NULL AND @UserID = NULL)
BEGIN
	SELECT 
		MAct.ModerationAction, 
		Total = (SELECT COUNT(MA.ModerationAction) FROM cs_ModerationAudit MA 
			WHERE MA.PostID = @PostID AND  MA.SettingsID =  @SettingsID AND MAct.ModerationAction = MA.ModerationAction 
			GROUP BY MA.ModerationAction)
	FROM 
		cs_ModerationAction MAct

END
ELSE IF (@UserID != NULL AND @PostID = NULL)
BEGIN
	SELECT 
		MAct.ModerationAction, 
		Total = (SELECT COUNT(MA.ModerationAction) FROM cs_ModerationAudit MA 
			WHERE MA.UserID = @UserID AND  MA.SettingsID =  @SettingsID AND MAct.ModerationAction = MA.ModerationAction 
			GROUP BY MA.ModerationAction)
	FROM 
		cs_ModerationAction MAct
END
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].cs_ModerationAudit_Summary_Get to public
go

/***********************************************
* Sproc: cs_ModerationAudit_User_Get
* File Date: 11/29/2006 10:07:31 AM
***********************************************/
Print 'Creating...cs_ModerationAudit_User_Get'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_ModerationAudit_User_Get]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_ModerationAudit_User_Get]
GO

CREATE PROCEDURE [dbo].cs_ModerationAudit_User_Get
(
	@UserID int,
	@ModerationAction int,
	@PageIndex int,
	@PageSize int,
	@ReturnRecordCount bit,
	@SettingsID int
)
AS
SET Transaction Isolation Level Read UNCOMMITTED

--
-- IF @UserActionsFilter = 1 then we want to have the following moderation actions for provided UserID:
-- baan (12), unban (13), moderate (11), unmoderate (10), rst passwd (14), chg passwd (15), edit user (9);
-- OTHERWISE we want to these moderation actions:
-- post approved (1), post edited (2), post moved (3), post deleted (4), 5, 6, 7, 8
--
-- Sometimes the moderator is the user itself, so take both of them into account
--

DECLARE @PageLowerBound int
DECLARE @PageUpperBound int

-- First set the rowcount
DECLARE @RowsToReturn int
SET @RowsToReturn = @PageSize * (@PageIndex + 1)
SET ROWCOUNT @RowsToReturn

-- Set the page bounds
SET @PageLowerBound = @PageSize * @PageIndex
SET @PageUpperBound = @PageLowerBound + @PageSize + 1

-- Create a temp table to store the select results
CREATE TABLE #TmpPageIndex 
(
	IndexID int IDENTITY (1, 1) NOT NULL,
	ID int
)

CREATE INDEX page_index ON #TmpPageIndex(IndexID)

-- Select records
INSERT INTO #TmpPageIndex (ID)
	SELECT ID FROM cs_ModerationAudit (nolock) 
	WHERE UserID = @UserID AND ModerationAction = @ModerationAction AND SettingsID = @SettingsID
	ORDER BY ModeratedOn ASC

SELECT
	MA.*,
	U.UserName AS ModeratorName
FROM 
	cs_ModerationAudit MA (nolock) LEFT JOIN cs_vw_Users_FullUser U ON U.cs_UserID = MA.ModeratorID,
	#TmpPageIndex
WHERE 
	MA.ID = #TmpPageIndex.ID AND
	#TmpPageIndex.IndexID > @PageLowerBound AND
	#TmpPageIndex.IndexID < @PageUpperBound AND 
	MA.SettingsID = @SettingsID
ORDER BY
	IndexID

IF @ReturnRecordCount = 1
	SELECT COUNT(UserID) 
	FROM cs_ModerationAudit (nolock) 
	WHERE UserID = @UserID AND ModerationAction = @ModerationAction AND SettingsID = @SettingsID
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].cs_ModerationAudit_User_Get to public
go

/***********************************************
* Sproc: cs_ModerationAudit_User_SaveEvent
* File Date: 11/29/2006 10:07:31 AM
***********************************************/
Print 'Creating...cs_ModerationAudit_User_SaveEvent'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_ModerationAudit_User_SaveEvent]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_ModerationAudit_User_SaveEvent]
GO

CREATE   procedure [dbo].cs_ModerationAudit_User_SaveEvent
(
	@UserID int,
	@ModeratorID int,
	@PasswordChanged bit = 0,
	@PasswordReset bit = 0,
	@UserBanned bit = 0,
	@BanDetails nvarchar(1024) = '',
	@UserUnbanned bit = 0,
	@UserEdited bit = 0,
	@UserModerated bit = 0,
	@UserIgnored bit = 0,
	@UserUnignored bit = 0,
	@SettingsID int
)
AS
SET Transaction Isolation Level Read UNCOMMITTED
BEGIN

	IF @PasswordReset = 1
		exec cs_system_ModerationAction_AuditEntry 14, @ModeratorID, null, @UserID, null, @SettingsID, 'User password has been reset.'
	ELSE IF @PasswordChanged = 1
		exec cs_system_ModerationAction_AuditEntry 15, @ModeratorID, null, @UserID, null, @SettingsID, 'User password has been changed.'
	ELSE IF @UserBanned = 1
		exec cs_system_ModerationAction_AuditEntry 12, @ModeratorID, null, @UserID, null, @SettingsID, @BanDetails
	ELSE IF @UserUnbanned = 1
		exec cs_system_ModerationAction_AuditEntry 13, @ModeratorID, null, @UserID, null, @SettingsID, 'User profile  has been un-banned.'
	ELSE IF @UserEdited = 1
		exec cs_system_ModerationAction_AuditEntry 9, @ModeratorID, null, @UserID, null, @SettingsID, 'User profile has been updated.'
	ELSE IF @UserModerated = 1
		exec cs_system_ModerationAction_AuditEntry 11, @ModeratorID, null, @UserID, null, @SettingsID, 'User is moderated.'
	ELSE IF @UserIgnored = 1
		exec cs_system_ModerationAction_AuditEntry 20, @ModeratorID, null, @UserID, null, @SettingsID, 'User has been set to ignored.'
	ELSE IF @UserUnignored = 1
		exec cs_system_ModerationAction_AuditEntry 21, @ModeratorID, null, @UserID, null, @SettingsID, 'User has been unignored.'
	ELSE IF @UserModerated = 0
		exec cs_system_ModerationAction_AuditEntry 10, @ModeratorID, null, @UserID, null, @SettingsID, 'User is not moderated.'
END


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



grant execute on [dbo].cs_ModerationAudit_User_SaveEvent to public
go

/***********************************************
* Sproc: cs_nntp_GetArticlesToPost
* File Date: 11/29/2006 10:07:31 AM
***********************************************/
Print 'Creating...cs_nntp_GetArticlesToPost'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO


if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_nntp_GetArticlesToPost]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_nntp_GetArticlesToPost]
GO

create procedure [dbo].cs_nntp_GetArticlesToPost
(
	@SectionID int
)
AS
DECLARE @MaxPostID int
DECLARE @ThreadID int
DECLARE @ParentID int
DECLARE @PostAuthor nvarchar(128)
DECLARE @Subject nvarchar(512)
DECLARE @PostDate datetime
DECLARE @SiteUrl nvarchar(512)

SET @MaxPostID = (SELECT max(PostID) FROM cs_nntp_Posts WHERE SectionID = @SectionID)

SET @SiteUrl = (	SELECT 
				SiteUrl 
			FROM 
				cs_Sites S, 
				cs_Sections SN,
				cs_SiteMappings F 
			WHERE 
				F.SiteID = S.SiteID AND 
				SN.SettingsID = F.SettingsID AND
				SN.SectionID = @SectionID
		)

CREATE TABLE #PostIndex 
(
	PostID int,
	NntpUniqueID nvarchar(1024)
)

-- Temporary table for values we need to operate on
INSERT INTO #PostIndex (PostID, NntpUniqueID)
SELECT 
	PostID = P.PostID,
	NntpUniqueID = ('<' + CAST(P.PostID as nvarchar(64)) + '-' + CAST(P.ThreadID as nvarchar(64)) + '-' + CAST(P.ParentID as nvarchar(64)) + '@' + (@SiteUrl) + '>')
FROM 
	cs_Posts P
WHERE 
	P.PostID > @MaxPostID AND
	P.SectionID = @SectionID

-- Return values
SELECT 
	NntpReferenceId = (SELECT NntpUniqueID FROM cs_nntp_Posts WHERE PostID = P.ParentID),
	NntpGroup = (SELECT NntpGroup FROM cs_nntp_NewsGroups WHERE SectionID = @SectionID),
	P1.NntpUniqueID,
	P.*
FROM 
	cs_Posts P,
	#PostIndex P1
WHERE 
	P.PostID = P1.PostID

-- Mark items as NNTP Posts
INSERT INTO cs_nntp_Posts
SELECT 
	P.PostID,
	P.SectionID,
	0,
	P1.NntpUniqueID,
	P.SettingsID
FROM 
	cs_Posts P,
	#PostIndex P1
WHERE 
	P.PostID = P1.PostID
	




GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO




grant execute on [dbo].[cs_nntp_GetArticlesToPost] to public
go
/***********************************************
* Sproc: cs_nntp_GetForumNewsgroups
* File Date: 11/29/2006 10:07:32 AM
***********************************************/
Print 'Creating...cs_nntp_GetForumNewsgroups'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_nntp_GetForumNewsgroups]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_nntp_GetForumNewsgroups]
GO



CREATE    procedure [dbo].cs_nntp_GetForumNewsgroups
AS
SET Transaction Isolation Level Read UNCOMMITTED
BEGIN

	SELECT 
		*
	FROM 
		cs_nntp_Newsgroups 

END


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_nntp_GetForumNewsgroups] to public
go
/***********************************************
* Sproc: cs_nntp_GetLastArticleId
* File Date: 11/29/2006 10:07:33 AM
***********************************************/
Print 'Creating...cs_nntp_GetLastArticleId'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_nntp_GetLastArticleId]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_nntp_GetLastArticleId]
GO



CREATE    procedure [dbo].cs_nntp_GetLastArticleId
(
	@SectionID int
)
AS
SET Transaction Isolation Level Read UNCOMMITTED
BEGIN

	SELECT 
		MAX(NntpPostID + 1)
	FROM 
		cs_nntp_Posts 
	WHERE 
		SectionID = @SectionID

END


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_nntp_GetLastArticleId] to public
go
/***********************************************
* Sproc: cs_nntp_Post_Add
* File Date: 11/29/2006 10:07:31 AM
***********************************************/
Print 'Creating...cs_nntp_Post_Add'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_nntp_Post_Add]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_nntp_Post_Add]
GO

CREATE           procedure [dbo].cs_nntp_Post_Add
(
	@NntpPostID 		int,
	@SectionID 		int,
	@NntpUniqueID 		nvarchar(256),
	@NntpParentUniqueID	nvarchar(245) = null,
	@UserName 		nvarchar(256),
	@Email	 		nvarchar(256),
	@Subject		nvarchar(256),
	@Body			ntext,
	@FormattedBody		ntext,
	@PostDate		datetime
)
AS
SET Transaction Isolation Level Read UNCOMMITTED
BEGIN

DECLARE @ParentID int
DECLARE @PostID int
DECLARE @ThreadID int
DECLARE @UserID int
DECLARE @SettingsID int

SELECT @SettingsID = SettingsID FROM cs_Sections WHERE SectionID = @SectionID

-- Set the Parent ID to 0
SET @ParentID = 0

-- Attempt to find the user
SELECT @UserID = cs_UserID FROM cs_vw_Users_FullUser WHERE Email = @Email

-- Not linked via email
IF @UserID IS NULL
BEGIN
	-- Attempt to link via the username
	SELECT @UserID = cs_UserID FROM cs_vw_Users_FullUser WHERE UserName = @UserName

	-- Can't find the user
	IF @UserID IS NULL
	BEGIN

		EXEC cs_GetAnonymousUserID @SettingsID, @UserID output

	END
END

-- Already Added?
IF EXISTS (SELECT NntpPostID FROM cs_nntp_Posts WHERE NntpUniqueID = @NntpUniqueID)
	RETURN

-- Was a @NntpParentUniqueID specified?
IF @NntpParentUniqueID IS NOT NULL
BEGIN

	-- Attempt to find the ParentID of the Post
	SELECT 
		@ParentID = PostID
	FROM 
		cs_nntp_Posts 
	WHERE	
		NntpUniqueID = @NntpParentUniqueID

	IF @ParentID = 0
		RETURN
END

-- Insert the post into the cs_Posts table
exec cs_Post_CreateUpdate 
	@SectionID, 
	@ParentID, 
	1, 
	0,
	@Subject, 
	@UserID, 
	@UserName,
	@Body, 
	@FormattedBody, 
	0, 
	0, 
	0, 
	1,
	'1/1/1797', 
	0, 
	@PostDate, 
	'127.0.0.1', 
	null,
	null,
	@SettingsID,
	0,
	@PostID output,
	@ThreadID output

-- INSERT the post into the cs_nntp_Posts table
INSERT INTO
	cs_nntp_Posts
	(
		PostID,
		SectionID,
		NntpPostID,
		NntpUniqueID,
		SettingsID
	)
VALUES
	(
		@PostID,
		@SectionID,
		@NntpPostID,
		@NntpUniqueID,
		@SettingsID
	)

END



GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO


grant execute on [dbo].[cs_nntp_Post_Add] to public
go

/***********************************************
* Sproc: cs_OverviewActivityReportRecords_Get
* File Date: 11/29/2006 10:07:33 AM
***********************************************/
Print 'Creating...cs_OverviewActivityReportRecords_Get'

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_OverviewActivityReportRecords_Get]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_OverviewActivityReportRecords_Get]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO




CREATE PROC dbo.cs_OverviewActivityReportRecords_Get
(
	@BegReportDate datetime,
	@EndReportDate datetime
)

AS

/* # of new users in given time period */
SELECT COUNT(*) FROM aspnet_Membership
WHERE CreateDate BETWEEN @BegReportDate AND @EndReportDate


/* # of new threads in a given time period */
SELECT COUNT(*)
FROM cs_Threads
WHERE ThreadDate BETWEEN @BegReportDate AND @EndReportDate


/* # of new posts in a given time period */
SELECT COUNT(*)
FROM cs_Posts
WHERE PostDate BETWEEN @BegReportDate AND @EndReportDate



GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_OverviewActivityReportRecords_Get] to public
go
/***********************************************
* Sproc: cs_PageViews_Add
* File Date: 11/29/2006 10:07:34 AM
***********************************************/
Print 'Creating...cs_PageViews_Add'

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_PageViews_Add]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_PageViews_Add]
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



CREATE    Proc [dbo].cs_PageViews_Add
(
	@URL nvarchar(512),
	@VisitCount int
)
AS

DECLARE @DTStamp AS DateTime
SET @DTStamp = GetDate()

IF EXISTS (SELECT URL FROM cs_PageViews WHERE URL = @URL AND DATEDIFF(HOUR, DateTimeStamp, @DTStamp) < 1)
	UPDATE cs_PageViews
	SET cs_PageViews.VisitCount = cs_PageViews.VisitCount + @VisitCount
        WHERE URL = @URL
ELSE
	INSERT INTO cs_PageViews
		(URL, VisitCount, DateTimeStamp)
	VALUES
		(@URL, @VisitCount, @DTStamp)




GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_PageViews_Add] to public
go

/***********************************************
* Sproc: cs_PageViews_Get
* File Date: 11/29/2006 10:07:31 AM
***********************************************/
Print 'Creating...cs_PageViews_Get'

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_PageViews_Get]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_PageViews_Get]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO


CREATE      PROCEDURE [dbo].cs_PageViews_Get
(
	 @nRecordNumberStart INT
    	,@nRecordNumberEnd INT
        ,@BegReportDate DateTime
	,@EndReportDate DateTime
	,@Paged BIT
)

AS
BEGIN

-- declare @Paged BIT
-- set @Paged = 1
-- declare @EndReportDate DateTime
-- set @EndReportDate = '1/1/2008'
-- declare @BegReportDate DateTime
-- set @BegReportDate = '1/1/1900'
-- declare @nRecordNumberStart INT
-- set @nRecordNumberStart = 1
-- declare @nRecordNumberEnd INT
-- set @nRecordNumberEnd = 100

IF @Paged = 1
	BEGIN
		DECLARE @totalRecords INT
		--------------------------------------------------------------------
		-- Define the table to do the filtering and paging
		--------------------------------------------------------------------
		DECLARE @tblTempData TABLE
		(
			nID INT IDENTITY
			,URL varchar(512)
			,VisitCount INT
		)
		INSERT INTO @tblTempData
		(
			URL
			,VisitCount
		)
		SELECT
			URL, SUM(VisitCount) AS VisitCount
		FROM
			cs_PageViews AS PageViews
		WHERE 
			PageViews.DateTimeStamp between @BegReportDate and @EndReportDate
                GROUP BY
			URL
		ORDER BY
			VisitCount DESC
		SET @totalRecords = @@rowcount
		-------------------------------------------------------------------------------------
		
		SELECT
			URL
			,VisitCount
		FROM
			@tblTempData 
		WHERE
			nID BETWEEN @nRecordNumberStart AND @nRecordNumberEnd
		ORDER BY 
			nID ASC
		
		--Return Record Count
		SELECT @totalRecords
	END
ELSE
	BEGIN
		SELECT
			URL, SUM(VisitCount) AS VisitCount
		FROM
			cs_PageViews AS PageViews
		WHERE 
			PageViews.DateTimeStamp between @BegReportDate and @EndReportDate
                GROUP BY
			URL
		ORDER BY
			VisitCount DESC
	END
END                                                                                                                                                                                                                               


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_PageViews_Get] to public
go

/***********************************************
* Sproc: cs_Page_Visits_Add
* File Date: 11/29/2006 10:07:31 AM
***********************************************/
Print 'Creating...cs_Page_Visits_Add'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Page_Visits_Add]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Page_Visits_Add]
GO

CREATE  Proc [dbo].cs_Page_Visits_Add
(
	@IP nvarchar(20),
	@VisitCount int
)
AS

DECLARE @DTStamp AS DateTime
SET @DTStamp = GetDate()

INSERT INTO cs_Visits
		(IP, VisitCount, DateTimeStamp)
	VALUES
		(@IP, @VisitCount, @DTStamp)



GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].cs_Page_Visits_Add to public
go

/***********************************************
* Sproc: cs_Points_CalculateForPost
* File Date: 11/29/2006 10:07:31 AM
***********************************************/
Print 'Creating...cs_Points_CalculateForPost'

SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS ON
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Points_CalculateForPost]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Points_CalculateForPost]
GO
--------------------------------------------------------------------------------
--	cs_Points_CalculateForPost
--	Calculates the points for a post
--------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[cs_Points_CalculateForPost]
(
	@SettingsID			int,
	@PostID				int,
	@PostFactor			int,
	@ReplyFactor		int,
	@ReplierFactor		int,
	@RatingFactor		int,
	@DownloadFactor		int,
	@DownloaderFactor	int,
	@FavoritePostFactor	int,
	@ForumRatingType	int
)
AS
	SET NOCOUNT ON
	SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED


	-- get post's reply count
	DECLARE		@ReplyCount		int,
				@ReplierCount	int
	SELECT		@ReplyCount = COUNT(P.PostID),
				@ReplierCount = COUNT(DISTINCT(P.UserID))
	FROM		cs_Posts PP
	INNER JOIN	cs_Posts P
		ON		PP.PostID = P.ParentID
	INNER JOIN	cs_Sections S				-- exclude private messages
		ON		PP.SectionID = S.SectionID
	WHERE		PP.PostID = @PostID
		AND		PP.SettingsID = @SettingsID
		AND		S.EnablePostPoints = 1		-- ignore excluded sections
		AND		PP.UserID <> P.UserID		-- ignore self-replies
		AND		PP.PostID <> P.PostID		-- ignore thread starters
		AND		P.IsApproved = 1			-- ignore posts awaiting moderation


	-- get post's rating sum
	DECLARE		@RatingSum	int
	SELECT		@RatingSum = ISNULL(SUM(PR.Rating), 0)
	FROM		cs_PostRating PR
	INNER JOIN	cs_Posts P
		ON		PR.PostID = P.PostID
	INNER JOIN	cs_Sections S				-- exclude private messages
		ON		P.SectionID = S.SectionID
	WHERE		PR.PostID = @PostID
		AND		PR.SettingsID = @SettingsID
		AND		S.EnablePostPoints = 1		-- ignore excluded sections
		AND		PR.UserID <> P.UserID		-- ignore self-ratings
		AND		P.IsApproved = 1			-- ignore posts awaiting moderation
		AND		@ForumRatingType = 1		-- only used if setup for post rating; ignore thread rating


	-- get post's download count
	DECLARE		@DownloadCount		int,
				@DownloaderCount	int
	SELECT		@DownloadCount = COUNT(D.PostID),
				@DownloaderCount = COUNT(DISTINCT(D.UserID))
	FROM		files_Downloads D
	INNER JOIN	cs_Posts P
		ON		D.PostID = P.PostID
	INNER JOIN	cs_Sections S
		ON		P.SectionID = S.SectionID
	WHERE		D.PostID = @PostID
		AND		P.SettingsID = @SettingsID
		AND		S.EnablePostPoints = 1		-- ignore excluded sections
		AND		D.UserID <> P.UserID		-- ignore self-authored favorites
		AND		P.IsApproved = 1			-- ignore posts awaiting moderation


	-- get post's favorite count
	DECLARE		@FavoriteCount	int
	SELECT		@FavoriteCount = COUNT(FP.PostID)
	FROM		cs_FavoritePosts FP
	INNER JOIN	cs_Posts P
		ON		FP.PostID = P.PostID
	INNER JOIN	cs_Sections S				-- exclude private messages
		ON		P.SectionID = S.SectionID
	WHERE		FP.PostID = @PostID
		AND		P.SettingsID = @SettingsID
		AND		S.EnablePostPoints = 1		-- ignore excluded sections
		AND		FP.OwnerID <> P.UserID		-- ignore self-authored favorites
		AND		P.IsApproved = 1			-- ignore posts awaiting moderation


	-- update post points
	UPDATE		P
	SET			Points =
				1 * @PostFactor
				+ @ReplyCount * @ReplyFactor
				+ @ReplierCount * @ReplierFactor
				+ @RatingSum * @RatingFactor
				+ @DownloadCount * @DownloadFactor
				+ @DownloaderCount * @DownloaderFactor
				+ @FavoriteCount * @FavoritePostFactor,
				PointsUpdated = GETDATE()
	FROM		cs_Posts P
	INNER JOIN	cs_Sections S				-- exclude private messages
		ON		P.SectionID = S.SectionID
	WHERE		P.PostID = @PostID
		AND		P.SettingsID = @SettingsID
		AND		S.EnablePostPoints = 1		-- ignore excluded sections
		AND		P.IsApproved = 1			-- ignore posts awaiting moderation


	RETURN
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO

GRANT EXECUTE on [dbo].[cs_Points_CalculateForPost] to [public]

/***********************************************
* Sproc: cs_Points_CalculateForPostAndAuthor
* File Date: 11/29/2006 10:07:32 AM
***********************************************/
Print 'Creating...cs_Points_CalculateForPostAndAuthor'

SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS ON
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Points_CalculateForPostAndAuthor]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Points_CalculateForPostAndAuthor]
GO
--------------------------------------------------------------------------------
--	cs_Points_CalculateForPostAndAuthor
--	Calculates the points for a post and its author
--------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[cs_Points_CalculateForPostAndAuthor]
(
	@SettingsID			int,
	@PostID				int,
	@PostFactor			int,
	@ReplyFactor		int,
	@ReplierFactor		int,
	@RatingFactor		int,
	@DownloadFactor		int,
	@DownloaderFactor	int,
	@FavoritePostFactor	int,
	@FavoriteUserFactor	int,
	@RaterFactor		int,
	@ForumRatingType	int
)
AS
	SET NOCOUNT ON
	SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED


	-- recalculate post points
	EXECUTE cs_Points_CalculateForPost @SettingsID, @PostID, @PostFactor, @ReplyFactor, @ReplierFactor, @RatingFactor, @DownloadFactor, @DownloaderFactor, @FavoritePostFactor, @ForumRatingType


	-- get post author
	DECLARE @UserID	int
	EXECUTE cs_Post_GetAuthorID @SettingsID, @PostID, @UserID OUTPUT


	-- recalculate author points
	EXECUTE cs_Points_CalculateForUser @SettingsID, @UserID, @FavoriteUserFactor, @RaterFactor, @ForumRatingType


	RETURN
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO

GRANT EXECUTE on [dbo].[cs_Points_CalculateForPostAndAuthor] to [public]

/***********************************************
* Sproc: cs_Points_CalculateForPost_Set
* File Date: 11/29/2006 10:07:31 AM
***********************************************/
Print 'Creating...cs_Points_CalculateForPost_Set'

SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS ON
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Points_CalculateForPost_Set]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Points_CalculateForPost_Set]
GO
--------------------------------------------------------------------------------
--	cs_Points_CalculateForPost_Set
--	Calculates the points for a post set
--------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[cs_Points_CalculateForPost_Set]
(
	@SettingsID			int,
	@FilterType			int,
	@FilterValue		int,
	@PostFactor			int,
	@ReplyFactor		int,
	@ReplierFactor		int,
	@RatingFactor		int,
	@DownloadFactor		int,
	@DownloaderFactor	int,
	@FavoritePostFactor	int,
	@ForumRatingType	int
)
AS
	SET NOCOUNT ON
	SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED

	-- declare temp structures
	CREATE TABLE	#PostSet		(PostID int)
	CREATE TABLE	#ReplyData		(PostID int, ReplyCount int, ReplierCount int)
	CREATE TABLE	#RatingData		(PostID int, RatingSum int)
	CREATE TABLE	#DownloadData	(PostID int, DownloadCount int, DownloaderCount int)
	CREATE TABLE	#FavoriteData	(PostID int, Value int)


	-- get working post set
	INSERT INTO	#PostSet
				(PostID)
	EXECUTE		cs_Posts_GetPostIDByFilter @SettingsID, @FilterType, @FilterValue


	-- get post's reply statistics
	INSERT INTO	#ReplyData
				(PostID, ReplyCount, ReplierCount)
	SELECT		PP.PostID, COUNT(P.PostID), COUNT(DISTINCT(P.UserID))
	FROM		cs_Posts PP
	INNER JOIN	cs_Posts P
		ON		PP.PostID = P.ParentID
	INNER JOIN	#PostSet PS
		ON		PP.PostID = PS.PostID
	WHERE		PP.SettingsID = @SettingsID
		AND		PP.UserID <> P.UserID		-- ignore self-replies
		AND		PP.PostID <> P.PostID		-- ignore thread starters
	GROUP BY	PP.PostID


	-- get post's rating statistics
	INSERT INTO	#RatingData
				(PostID, RatingSum)
	SELECT		PR.PostID, ISNULL(SUM(PR.Rating), 0)
	FROM		cs_PostRating PR
	INNER JOIN	cs_Posts P
		ON		PR.PostID = P.PostID
	INNER JOIN	#PostSet PS
		ON		PR.PostID = PS.PostID
	WHERE		PR.SettingsID = @SettingsID
		AND		PR.UserID <> P.UserID		-- ignore self-ratings
		AND		@ForumRatingType = 1		-- only used if setup for post rating; ignore thread rating
	GROUP BY	PR.PostID


	-- get post's download statistics
	INSERT INTO	#DownloadData
				(PostID, DownloadCount, DownloaderCount)
	SELECT		D.PostID, COUNT(D.PostID), COUNT(DISTINCT(D.UserID))
	FROM		files_Downloads D
	INNER JOIN	cs_Posts P
		ON		D.PostID = P.PostID
	INNER JOIN	#PostSet PS
		ON		D.PostID = PS.PostID
	WHERE		P.SettingsID = @SettingsID
		AND		D.UserID <> P.UserID		-- ignore self-downloads
	GROUP BY	D.PostID


	-- get post's favorite count
	INSERT INTO	#FavoriteData
				(PostID, Value)
	SELECT		FP.PostID, COUNT(FP.PostID)
	FROM		cs_FavoritePosts FP
	INNER JOIN	cs_Posts P
		ON		FP.PostID = P.PostID
	INNER JOIN	#PostSet PS
		ON		FP.PostID = PS.PostID
	WHERE		FP.SettingsID = @SettingsID
		AND		FP.OwnerID <> P.UserID
	GROUP BY	FP.PostID


	-- disable triggers (nntp triggers make this update deathly SLOW!)
	ALTER TABLE cs_posts DISABLE TRIGGER ALL


	-- update post points
	UPDATE		P
	SET			Points =
				1 * @PostFactor
				+ ISNULL(RPD.ReplyCount, 0) * @ReplyFactor
				+ ISNULL(RPD.ReplierCount, 0) * @ReplierFactor
				+ ISNULL(RTD.RatingSum, 0) * @RatingFactor
				+ ISNULL(DD.DownloadCount, 0) * @DownloadFactor
				+ ISNULL(DD.DownloaderCount, 0) * @DownloaderFactor
				+ ISNULL(FD.Value, 0) * @FavoritePostFactor,
				PointsUpdated = GETDATE()
	FROM		cs_Posts P
	INNER JOIN	#PostSet PS
		ON		P.PostID = PS.PostID
	LEFT JOIN	#ReplyData RPD
		ON		P.PostID = RPD.PostID
	LEFT JOIN	#RatingData RTD
		ON		P.PostID = RTD.PostID
	LEFT JOIN	#DownloadData DD
		ON		P.PostID = DD.PostID
	LEFT JOIN	#FavoriteData FD
		ON		P.PostID = FD.PostID
	WHERE		P.SettingsID = @SettingsID


	-- enable triggers
	ALTER TABLE cs_posts ENABLE TRIGGER ALL


	-- clean up
	DROP TABLE	#FavoriteData
	DROP TABLE	#DownloadData
	DROP TABLE	#RatingData
	DROP TABLE	#ReplyData
	DROP TABLE	#PostSet


	RETURN
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO

GRANT EXECUTE on [dbo].[cs_Points_CalculateForPost_Set] to [public]

/***********************************************
* Sproc: cs_Points_CalculateForUser
* File Date: 11/29/2006 10:07:30 AM
***********************************************/
Print 'Creating...cs_Points_CalculateForUser'

SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS ON
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Points_CalculateForUser]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Points_CalculateForUser]
GO
--------------------------------------------------------------------------------
--	cs_Points_CalculateForUser
--	Calculates the points for a user
--------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[cs_Points_CalculateForUser]
(
	@SettingsID			int,
	@UserID				int,
	@FavoriteUserFactor	int,
	@RaterFactor		int,
	@ForumRatingType	int,
	@UpdateAllSettingsID bit = 0
)
AS
	SET NOCOUNT ON
	SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED


	-- get user's post points
	DECLARE		@PostPoints		int
	SELECT		@PostPoints = ISNULL(SUM(P.Points), 0)
	FROM		cs_Posts P
	INNER JOIN	cs_Sections S				-- exclude private messages
		ON		P.SectionID = S.SectionID
	WHERE		P.UserID = @UserID
		AND		(P.SettingsID = @SettingsID or @UpdateAllSettingsID = 1)
		AND		S.EnablePostPoints = 1		-- ignore excluded sections
		AND		P.IsApproved = 1			-- ignore posts awaiting moderation


	-- get user's favorite count
	DECLARE		@FavoriteUserCount	int
	SELECT		@FavoriteUserCount = COUNT(FU.OwnerID)
	FROM		cs_FavoriteUsers FU
	WHERE		FU.UserID = @UserID
		AND		(FU.SettingsID = @SettingsID or @UpdateAllSettingsID = 1)
		AND		FU.UserID <> FU.OwnerID			-- ignore self-favorites


	-- get user's rating sum
	DECLARE		@RatingSum	int
	SELECT		@RatingSum = ISNULL(SUM(PR.Rating), 0)
	FROM		cs_PostRating PR
	INNER JOIN	cs_Posts P
		ON		PR.PostID = P.PostID
	INNER JOIN	cs_Sections S				-- exclude private messages
		ON		P.SectionID = S.SectionID
	WHERE		PR.UserID = @UserID
		AND		(P.SettingsID = @SettingsID or @UpdateAllSettingsID = 1)
		AND		S.EnablePostPoints = 1		-- ignore excluded sections
		AND		PR.UserID <> P.UserID		-- ignore self-ratings
		AND		P.IsApproved = 1			-- ignore posts awaiting moderation
		AND		@ForumRatingType = 1		-- only used if setup for post rating; ignore thread rating


	-- update user points
	UPDATE		UP
	SET			Points =
					1 * @PostPoints
					+ @FavoriteUserCount * @FavoriteUserFactor
					+ @RatingSum * @RaterFactor,
				PointsUpdated = GETDATE()
	FROM		cs_UserProfile UP
	WHERE		UP.UserID = @UserID
		AND		(UP.SettingsID = @SettingsID or @UpdateAllSettingsID = 1)


	RETURN
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO

GRANT EXECUTE on [dbo].[cs_Points_CalculateForUser] to [public]

/***********************************************
* Sproc: cs_Points_CalculateForUser_Set
* File Date: 11/29/2006 10:07:31 AM
***********************************************/
Print 'Creating...cs_Points_CalculateForUser_Set'

SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS ON
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Points_CalculateForUser_Set]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Points_CalculateForUser_Set]
GO
--------------------------------------------------------------------------------
--	cs_Points_CalculateForUser_Set
--	Calculates the points for a user set
--------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[cs_Points_CalculateForUser_Set]
(
	@SettingsID			int,
	@FilterType			int,
	@FilterValue		varchar(255),
	@FavoriteUserFactor	int,
	@RaterFactor		int,
	@ForumRatingType	int,
	@UpdateAllSettingsID bit = 0
)
AS
	SET NOCOUNT ON
	SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED


	-- declare temp structures
	CREATE TABLE	#UserSet		(UserID int)
	CREATE TABLE	#PostData		(UserID int, Value int)
	CREATE TABLE	#FavoriteData	(UserID int, Value int)
	CREATE TABLE	#RatingData		(UserID int, Value int)


	-- get working user set
	INSERT INTO	#UserSet
				(UserID)
	EXECUTE		cs_Users_GetUserIDByFilter @SettingsID, @FilterType, @FilterValue


	-- get user's post points
	INSERT INTO	#PostData
				(UserID, Value)
	SELECT		P.UserID, SUM(P.Points)
	FROM		cs_Posts P
	INNER JOIN	cs_Sections S				-- exclude private messages
		ON		P.SectionID = S.SectionID
	INNER JOIN	#UserSet US
		ON		P.UserID = US.UserID
	WHERE		(P.SettingsID = @SettingsID or @UpdateAllSettingsID = 1)
		AND		S.EnablePostPoints = 1		-- ignore excluded sections
		AND		P.IsApproved = 1			-- ignore posts awaiting moderation
	GROUP BY	P.UserID


	-- get user's favorite count
	INSERT INTO	#FavoriteData
				(UserID, Value)
	SELECT		FU.UserID, COUNT(FU.OwnerID)
	FROM		cs_FavoriteUsers FU
	INNER JOIN	#UserSet US
		ON		FU.UserID = US.UserID
	WHERE		(FU.SettingsID = @SettingsID or @UpdateAllSettingsID = 1)
		AND		FU.UserID <> FU.OwnerID			-- ignore self-favorites
	GROUP BY	FU.UserID


	-- get user's rating sum
	INSERT INTO	#RatingData
				(UserID, Value)
	SELECT		PR.UserID, ISNULL(SUM(PR.Rating), 0)
	FROM		cs_PostRating PR
	INNER JOIN	cs_Posts P
		ON		PR.PostID = P.PostID
	INNER JOIN	cs_Sections S				-- exclude private messages
		ON		P.SectionID = S.SectionID
	INNER JOIN	#UserSet US
		ON		PR.UserID = US.UserID
	WHERE		(PR.SettingsID = @SettingsID or @UpdateAllSettingsID = 1)
		AND		S.EnablePostPoints = 1		-- ignore excluded sections
		AND		PR.UserID <> P.UserID		-- ignore self-ratings
		AND		P.IsApproved = 1			-- ignore posts awaiting moderation
		AND		@ForumRatingType = 1		-- only used if setup for post rating; ignore thread rating
	GROUP BY	PR.UserID


	-- update user points
	UPDATE		UP
	SET			Points =
					ISNULL(PD.Value, 0)	* 1
					+ ISNULL(FD.Value, 0) * @FavoriteUserFactor
					+ ISNULL(RD.Value, 0) * @RaterFactor,
				PointsUpdated = GETDATE()
	FROM		cs_UserProfile UP
	INNER JOIN	#UserSet US
		ON		UP.UserID = US.UserID
	LEFT JOIN	#PostData PD
		ON		UP.UserID = PD.UserID
	LEFT JOIN	#FavoriteData FD
		ON		UP.UserID = FD.UserID
	LEFT JOIN	#RatingData RD
		ON		UP.UserID = RD.UserID
	WHERE		(UP.SettingsID = @SettingsID or @UpdateAllSettingsID = 1)


	-- clean up
	DROP TABLE	#RatingData
	DROP TABLE	#FavoriteData
	DROP TABLE	#PostData
	DROP TABLE	#UserSet


	RETURN
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO

GRANT EXECUTE on [dbo].[cs_Points_CalculateForUser_Set] to [public]

/***********************************************
* Sproc: cs_PostAttachment
* File Date: 11/29/2006 10:07:30 AM
***********************************************/
Print 'Creating...cs_PostAttachment'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_PostAttachment]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_PostAttachment]
GO







create procedure [dbo].cs_PostAttachment
(
	@PostID int,
	@MetaOnly bit = 0
)
AS
SET Transaction Isolation Level Read UNCOMMITTED
BEGIN

	if(@MetaOnly = 0)
	Begin

		SELECT
			[PostID], [SectionID], [UserID], [Created], [FileName], [Content], 
			[ContentType], [ContentSize], [SettingsID], [IsRemote], [Height], [Width], [FriendlyFileName]
		FROM
			cs_PostAttachments
		WHERE
			PostID = @PostID
	End
	ELSE
	Begin
		SELECT
			[PostID], [SectionID], [UserID], [Created], [FileName], null as [Content], 
			[ContentType], [ContentSize], [SettingsID], [IsRemote], [Height], [Width], [FriendlyFileName]
		FROM
			cs_PostAttachments
		WHERE
			PostID = @PostID

	End
END







GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_PostAttachment] to public
go
/***********************************************
* Sproc: cs_PostAttachment_Add
* File Date: 11/29/2006 10:07:33 AM
***********************************************/
Print 'Creating...cs_PostAttachment_Add'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_PostAttachment_Add]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_PostAttachment_Add]
GO











CREATE procedure dbo.cs_PostAttachment_Add 
(
	@PostID int,
	@UserID int,
	@SectionID int,
	@Filename nvarchar(1024),
	@FriendlyFileName nvarchar(256) = null,
	@Content image = null,
	@ContentType nvarchar(50),
	@ContentSize int,
	@IsRemote int,
	@SettingsID int,
	@Height int = 0,
	@Width int = 0
)
AS
SET Transaction Isolation Level Read UNCOMMITTED
BEGIN

	IF EXISTS (SELECT PostID FROM cs_PostAttachments WHERE PostID = @PostID and SettingsID = @SettingsID )
	begin
		UPDATE cs_PostAttachments SET
			[FileName] 	= @Filename,
			[FriendlyFileName] = @FriendlyFileName,
			Content		= @Content,
			ContentSize	= @ContentSize,
			IsRemote	= @IsRemote,
			[Height] 	= @Height,
			[Width]		= @Width
		WHERE
			PostID		= @PostID and
			SettingsID	= @SettingsID	
	end
	else
	begin
		INSERT INTO 
			cs_PostAttachments
		(
			PostID,
			SectionID,
			UserID,
			[FileName],
			[FriendlyFileName],
			Content,
			ContentType,
			ContentSize,
			IsRemote,
			SettingsID,
			[Height],
			[Width]
		)
		VALUES
		(
			@PostID,
			@SectionID,
			@UserID,
			@Filename,
			@FriendlyFileName,
			@Content,
			@ContentType,
			@ContentSize,
			@IsRemote,
			@SettingsID,
			@Height,
			@Width
		)
	end
	EXEC cs_Section_DiskUsage_Update @SectionID, @SettingsID
END




GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_PostAttachment_Add] to public
go

/***********************************************
* Sproc: cs_PostAttachment_Delete
* File Date: 11/29/2006 10:07:33 AM
***********************************************/
Print 'Creating...cs_PostAttachment_Delete'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_PostAttachment_Delete]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_PostAttachment_Delete]
GO


CREATE PROCEDURE dbo.cs_PostAttachment_Delete
(
	@PostID int
)
AS
SET Transaction Isolation Level Read UNCOMMITTED
BEGIN

	DECLARE @SettingsID int
	DECLARE @SectionID int

	SELECT @SettingsID = SettingsID, @SectionID = SectionID FROM cs_PostAttachments WHERE PostID = @PostID

	DELETE FROM cs_PostAttachments WHERE PostID = @PostID
	
	EXEC cs_Section_DiskUsage_Update @SectionID, @SettingsID

END


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_PostAttachment_Delete] to public
go

/***********************************************
* Sproc: cs_PostAttachment_Temp_Create
* File Date: 11/29/2006 10:07:33 AM
***********************************************/
Print 'Creating...cs_PostAttachment_Temp_Create'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_PostAttachment_Temp_Create]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_PostAttachment_Temp_Create]
GO



CREATE Procedure [dbo].cs_PostAttachment_Temp_Create
(
	@UserID int,
	@SettingsID int,
	@SectionID int,
	@Filename nvarchar(1024),
	@FriendlyFileName nvarchar(256) = null,
	@Content image = null,
	@ContentType nvarchar(50),
	@ContentSize int,
	@IsRemote int,
	@AttachmentID uniqueidentifier,
	@Height int = 0,
	@Width int = 0
)

as
SET Transaction Isolation Level Read UNCOMMITTED

		INSERT INTO 
		cs_PostAttachments_TEMP
		(
			AttachmentID,
			SectionID,
			UserID,
			[FileName],
			[FriendlyFileName],
			Content,
			ContentType,
			ContentSize,
			IsRemote,
			SettingsID,
			Created,
			[Height],
			[Width]
		)
		VALUES
		(
			@AttachmentID,
			@SectionID,
			@UserID,
			@Filename,
			@FriendlyFileName,
			@Content,
			@ContentType,
			@ContentSize,
			@IsRemote,
			@SettingsID,
			getdate(),
			@Height,
			@Width
		)


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT  EXECUTE  ON [dbo].[cs_PostAttachment_Temp_Create]  TO [public]
GO


/***********************************************
* Sproc: cs_PostAttachment_Temp_Expire
* File Date: 11/29/2006 10:07:30 AM
***********************************************/
Print 'Creating...cs_PostAttachment_Temp_Expire'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_PostAttachment_Temp_Expire]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_PostAttachment_Temp_Expire]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON
GO

CREATE PROCEDURE dbo.cs_PostAttachment_Temp_Expire
(
	@Date datetime
)
AS
SET Transaction Isolation Level Read UNCOMMITTED
BEGIN

	DELETE FROM cs_PostAttachments_TEMP WHERE Created < @Date

END
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT  EXECUTE  ON [dbo].[cs_PostAttachment_Temp_Expire]  TO [public]
GO

/***********************************************
* Sproc: cs_PostAttachment_Temp_Get
* File Date: 11/29/2006 10:07:30 AM
***********************************************/
Print 'Creating...cs_PostAttachment_Temp_Get'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_PostAttachment_Temp_Get]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_PostAttachment_Temp_Get]
GO



set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON
go


CREATE procedure [dbo].[cs_PostAttachment_Temp_Get] 
(
	@UserID int,
	@SectionID int,
	@AttachmentID uniqueidentifier,
	@SettingsID int
)
AS
SET Transaction Isolation Level Read UNCOMMITTED
BEGIN

		SELECT
			-1 as [PostID],[SectionID], [UserID], [Created], [FileName], [Content], 
			[ContentType], [ContentSize], [SettingsID], [IsRemote], [FriendlyFileName], [Height], [Width]
		FROM
			cs_PostAttachments_TEMP
		WHERE
			AttachmentID = @AttachmentID and SettingsID = @SettingsID and UserID = @UserID and SectionID = @SectionID

END


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT  EXECUTE  ON [dbo].[cs_PostAttachment_Temp_Get]  TO [public]
GO


/***********************************************
* Sproc: cs_PostAttachment_ToggleTemporary
* File Date: 11/29/2006 10:07:33 AM
***********************************************/
Print 'Creating...cs_PostAttachment_ToggleTemporary'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_PostAttachment_ToggleTemporary]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_PostAttachment_ToggleTemporary]
GO


CREATE procedure dbo.cs_PostAttachment_ToggleTemporary 
(
	@PostID int,
	@UserID int,
	@SectionID int,
	@ClearContent bit,
	@FriendlyFileName nvarchar(256),
	@AttachmentID uniqueidentifier,
	@SettingsID int,
	@DeleteTempOnly bit = 0
)
AS
SET Transaction Isolation Level Read UNCOMMITTED
BEGIN

		SELECT
			@PostID as [PostID], [SectionID], [UserID], [Created], [FileName], [Content], 
			[ContentType], [ContentSize], [SettingsID], [IsRemote], [FriendlyFileName], [Height], [Width]
		FROM
			cs_PostAttachments_TEMP
		WHERE
			AttachmentID = @AttachmentID and SettingsID = @SettingsID and UserID = @UserID and SectionID = @SectionID

	if(@ClearContent = 1)
	Begin
		update cs_PostAttachments_TEMP
		Set Content = '0x'
  	        where AttachmentID = @AttachmentID and SettingsID = @SettingsID and UserID = @UserID and SectionID = @SectionID
	End

	IF(@DeleteTempOnly = 0)
	BEGIN
		IF EXISTS (SELECT PostID FROM cs_PostAttachments WHERE PostID = @PostID and SettingsID = @SettingsID )
		BEGIN
			UPDATE cs_PostAttachments SET
				cs_PostAttachments.[FileName] 	= T.[Filename],
				cs_PostAttachments.[FriendlyFileName] = IsNull(@FriendlyFileName,T.FriendlyFileName),
				cs_PostAttachments.ContentSize	= T.ContentSize,
				cs_PostAttachments.IsRemote	= T.IsRemote,
				cs_PostAttachments.Height	= T.Height,
				cs_PostAttachments.Width	= T.Width,
				cs_PostAttachments.Content = T.Content,
				cs_PostAttachments.ContentType = T.ContentType,
				cs_PostAttachments.Created = T.Created,
				cs_PostAttachments.UserID = T.UserID
			FROM cs_PostAttachments_TEMP T
			WHERE
				cs_PostAttachments.PostID = @PostID and
				cs_PostAttachments.SettingsID = @SettingsID and
				T.AttachmentID = @AttachmentID and T.SettingsID = @SettingsID and T.UserID = @UserID and T.SectionID = @SectionID
		END
		ELSE
		BEGIN
			INSERT INTO 
			cs_PostAttachments
			(
				PostID,
				SectionID,
				UserID,
				[FileName],
				[FriendlyFileName],
				Content,
				ContentType,
				ContentSize,
				IsRemote,
				SettingsID,
				Created,
				[Height],
				[Width]
			)
			Select @PostID,	T.SectionID,T.UserID,T.[Filename],IsNull(@FriendlyFileName,T.FriendlyFileName),T.Content, T.ContentType,
				T.ContentSize,	T.IsRemote, T.SettingsID,T.Created, T.Height, T.Width
			FROM cs_PostAttachments_TEMP T
			WHERE T.AttachmentID = @AttachmentID and T.SettingsID = @SettingsID and T.UserID = @UserID and T.SectionID = @SectionID
		END
	END

	DELETE FROM cs_PostAttachments_TEMP where AttachmentID = @AttachmentID and SettingsID = @SettingsID and UserID = @UserID and SectionID = @SectionID
	
	EXEC cs_Section_DiskUsage_Update @SectionID, @SettingsID
END




GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_PostAttachment_ToggleTemporary] to public
go

/***********************************************
* Sproc: cs_PostAttachment_Update
* File Date: 11/29/2006 10:07:34 AM
***********************************************/
Print 'Creating...cs_PostAttachment_Update'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_PostAttachment_Update]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure dbo.[cs_PostAttachment_Update]
GO

create procedure [dbo].cs_PostAttachment_Update 
(
	@PostID int,
	@UserID int,
	@SectionID int,
	@Filename nvarchar(1024),
	@FriendlyFileName nvarchar(256) = null,
	@Content image = null,
	@ContentType nvarchar(50),
	@ContentSize int,
	@IsRemote int,
	@SettingsID int,
	@MetaDataOnly bit,
	@Height int = 0,
	@Width int = 0
)
AS
SET Transaction Isolation Level Read UNCOMMITTED
BEGIN

	IF EXISTS (SELECT PostID FROM cs_PostAttachments WHERE PostID = @PostID and SettingsID = @SettingsID )
	begin
		UPDATE cs_PostAttachments SET
			[FileName] 	= @Filename,
			[FriendlyFileName] = @FriendlyFileName,
			ContentSize	= @ContentSize,
			IsRemote	= @IsRemote,
			[Height]	= @Height,
			[Width]		= @Width
		WHERE
			PostID		= @PostID and
			SettingsID	= @SettingsID	

		if(@MetaDataOnly = 0)
		Begin
			UPDATE cs_PostAttachments SET
			Content		= @Content
		WHERE
			PostID		= @PostID and
			SettingsID	= @SettingsID	
		End
	end
	
END



GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on dbo.[cs_PostAttachment_Update] to public
go
/***********************************************
* Sproc: cs_PostCategories_Get
* File Date: 11/29/2006 10:07:30 AM
***********************************************/
Print 'Creating...cs_PostCategories_Get'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_PostCategories_Get]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_PostCategories_Get]
GO

CREATE PROCEDURE dbo.cs_PostCategories_Get
	@SectionID int=0,
	@ApplicationKey nvarchar(256)=null
AS

SET Transaction Isolation Level Read UNCOMMITTED


if @ApplicationKey Is Not Null
begin
	SELECT
		C.CategoryID, C.SectionID, C.Name, C.IsEnabled, C.ParentID, C.Path, C.Description, C.SettingsID,
		C.TotalThreads, C.MostRecentPostDate, C.TotalSubThreads, C.MostRecentSubPostDate, C.DateCreated, C.FeaturedPostID
	FROM cs_Post_Categories C
	LEFT JOIN cs_Sections F ON F.SectionID = C.SectionID
	WHERE F.ApplicationKey = @ApplicationKey
end
else
begin
	SELECT
		C.CategoryID, C.SectionID, C.Name, C.IsEnabled, C.ParentID, C.Path, C.Description, C.SettingsID,
		C.TotalThreads, C.MostRecentPostDate, C.TotalSubThreads, C.MostRecentSubPostDate, C.DateCreated, C.FeaturedPostID
	FROM cs_Post_Categories C
	WHERE C.SectionID = @SectionID
end

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT  EXECUTE  ON [dbo].[cs_PostCategories_Get]  TO [public]
GO

/***********************************************
* Sproc: cs_PostCategories_Get_ByName
* File Date: 11/29/2006 10:07:30 AM
***********************************************/
Print 'Creating...cs_PostCategories_Get_ByName'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_PostCategories_Get_ByName]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_PostCategories_Get_ByName]
GO

CREATE PROCEDURE dbo.cs_PostCategories_Get_ByName
	@Name nvarchar(256),
	@SectionQuerySQL ntext,
	@SettingsID int
AS

SET Transaction Isolation Level Read UNCOMMITTED

CREATE TABLE #Sections
(
	SectionID int
)

INSERT INTO #Sections (SectionID)
EXEC (@SectionQuerySQL)

SELECT
	C.CategoryID, C.SectionID, C.Name, C.IsEnabled, C.ParentID, C.Path, C.Description, C.SettingsID,
	C.TotalThreads, C.MostRecentPostDate, C.TotalSubThreads, C.MostRecentSubPostDate, C.DateCreated, C.FeaturedPostID
FROM cs_Post_Categories C
WHERE C.SectionID in (select SectionID from #Sections)
	and C.SettingsID = @SettingsID
	and C.[Name] = @Name
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT  EXECUTE  ON [dbo].[cs_PostCategories_Get_ByName]  TO [public]
GO


/***********************************************
* Sproc: cs_PostCategories_Get_WithoutPosts
* File Date: 11/29/2006 10:07:33 AM
***********************************************/
Print 'Creating...cs_PostCategories_Get_WithoutPosts'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_PostCategories_Get_WithoutPosts]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_PostCategories_Get_WithoutPosts]
GO

CREATE PROCEDURE dbo.cs_PostCategories_Get_WithoutPosts
	@SectionQuerySQL ntext,
	@SettingsID int
AS

SET Transaction Isolation Level Read UNCOMMITTED

CREATE TABLE #Sections
(
	SectionID int
)

INSERT INTO #Sections (SectionID)
EXEC (@SectionQuerySQL)

SELECT
		C.CategoryID, C.SectionID, C.Name, C.IsEnabled, C.ParentID, C.Path, C.Description, C.SettingsID,
		C.TotalThreads, C.MostRecentPostDate, C.TotalSubThreads, C.MostRecentSubPostDate, C.DateCreated, C.FeaturedPostID
FROM cs_Post_Categories C
WHERE C.CategoryID not in (
		select CategoryID
		from cs_Posts_InCategories PiC
		inner join cs_Posts P on P.PostID = PiC.PostID
		where P.SectionID in (select SectionID from #Sections)
			and P.SettingsID = @SettingsID
		)
	and C.SectionID in (select SectionID from #Sections)
	and C.SettingsID = @SettingsID
	and C.CategoryID not in (
		select UpLevelID
		from cs_Post_Categories_Parents
		where SectionID in (select SectionID from #Sections)
			and UpLevelID <> CategoryID
		)	

DROP TABLE #Sections
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT  EXECUTE  ON [dbo].[cs_PostCategories_Get_WithoutPosts]  TO [public]
GO


/***********************************************
* Sproc: cs_PostCategories_Parents_RebuildIndex
* File Date: 11/29/2006 10:07:30 AM
***********************************************/
Print 'Creating...cs_PostCategories_Parents_RebuildIndex'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_PostCategories_Parents_RebuildIndex]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_PostCategories_Parents_RebuildIndex]
GO


CREATE PROCEDURE [dbo].[cs_PostCategories_Parents_RebuildIndex] @SectionID INT = NULL
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;

	--Create some temporary storage for the update
	DECLARE @pathtable TABLE(
		CategoryID int not null,
		UpLevelID int not null,
		[path] varchar(255),
		SectionID int not null,
		unique (CategoryID, UpLevelID))
	
	--Fix any orphaned categories
	UPDATE cs_Post_Categories SET ParentID = 0 WHERE CategoryID IN (SELECT CategoryID FROM cs_Post_Categories WHERE ParentID <> 0 AND ParentID NOT IN (SELECT CategoryID FROM cs_Post_Categories))

	IF @SectionID IS NULL
	BEGIN

		--every post category is at least in itself
		INSERT INTO @pathtable (SectionID, CategoryID, UpLevelID, [path]) SELECT  SectionID, CategoryID, CategoryID, '/' + Convert(varchar(10),CategoryID) + '/' FROM cs_Post_Categories
		
		--Get all the non parents parents
		INSERT INTO @pathtable (SectionID, CategoryID, UpLevelID, [path]) SELECT  SectionID, CategoryID, ParentID, '/' + Convert(varchar(10),ParentID) + '/' + Convert(varchar(10),CategoryID) + '/'  FROM cs_Post_Categories WHERE ParentID > 0
	

		--Recurse until we have reached the root for all
		WHILE @@Rowcount > 0
		BEGIN
			
			INSERT INTO @pathtable (SectionID, CategoryID, UpLevelID, [path]) 

			SELECT  C.SectionID, P.CategoryID, C.ParentID,  RIGHT('/' + Convert(varchar(10),C.ParentID) + P.[path], 255)
			FROM @pathtable P
				INNER JOIN cs_Post_Categories C ON C.CategoryID = UpLevelID
				LEFT OUTER JOIN @pathtable DUPE ON P.CategoryID = DUPE.CategoryID AND C.ParentID = DUPE.UpLevelID
			WHERE ParentID > 0
				AND DUPE.UpLevelID IS NULL

		END
	

	END
	ELSE
	BEGIN
		--every post category is at least in itself (for this section)
		INSERT INTO @pathtable (SectionID, CategoryID, UpLevelID, [path]) SELECT SectionID, CategoryID, CategoryID, '/' + Convert(varchar(10),CategoryID) + '/'  FROM cs_Post_Categories WHERE SectionID = @SectionID

		--Get all the non parents parents (for this section)
		INSERT INTO @pathtable (SectionID, CategoryID, UpLevelID, [path]) SELECT SectionID, CategoryID, ParentID, '/' + Convert(varchar(10),ParentID) + '/' + Convert(varchar(10),CategoryID) + '/'  FROM cs_Post_Categories WHERE ParentID > 0 AND SectionID = @SectionID

		--Recurse until we have reached the root for all (for this section)
		WHILE @@Rowcount > 0
		BEGIN
			INSERT INTO @pathtable (SectionID, CategoryID, UpLevelID, [path]) 

			SELECT C.SectionID, P.CategoryID, C.ParentID,   RIGHT('/' + Convert(varchar(10),C.ParentID) + P.[path], 255)
			FROM @pathtable P
				INNER JOIN cs_Post_Categories C ON C.CategoryID = UpLevelID
				LEFT OUTER JOIN @pathtable DUPE ON P.CategoryID = DUPE.CategoryID AND C.ParentID = DUPE.UpLevelID
			WHERE ParentID > 0
				AND DUPE.UpLevelID IS NULL AND C.SectionID = @SectionID
		END
	END

	--Recalculate category stats for selected section
	UPDATE cs_Post_Categories SET
		TotalSubThreads = QSUB.posts,
		MostRecentSubPostDate = QSUB.postdate,
		TotalThreads = QCURR.posts,
		MostRecentPostDate = QCURR.postdate
	FROM cs_Post_Categories 
	INNER JOIN (
	SELECT P.UplevelID CategoryID, COUNT(PIC.PostID) posts, MAX(jP.PostDate) postdate 
	FROM 
		cs_Posts_InCategories PIC 
		INNER JOIN cs_Posts jP ON (jP.PostID = PIC.PostID AND jP.PostID = jP.ParentID) 
		INNER JOIN @pathtable P ON PIC.CategoryID = P.CategoryID
		INNER JOIN cs_Post_Categories C ON C.CategoryID = P.CategoryID

	GROUP BY P.UpLevelID
	) QSUB ON cs_Post_Categories.CategoryID = QSUB.CategoryID

	INNER JOIN (
	SELECT C.CategoryID CategoryID, COUNT(PIC.PostID) posts, MAX(jP.PostDate) postdate 
	FROM 
		cs_Posts_InCategories PIC 
		INNER JOIN cs_Posts jP ON (jP.PostID = PIC.PostID AND jP.PostID = jP.ParentID) 
		INNER JOIN cs_Post_Categories C ON C.CategoryID = PIC.CategoryID
	GROUP BY C.CategoryID
	) QCURR ON cs_Post_Categories.CategoryID = QCURR.CategoryID

	--clear current table data for new values
	IF @SectionID IS NULL
		TRUNCATE TABLE cs_Post_Categories_Parents
	ELSE
		DELETE FROM cs_Post_Categories_Parents WHERE SectionID = @SectionID

	--Commit the path table for use in adding / deleting posts in categories
	INSERT INTO cs_Post_Categories_Parents (SectionID, CategoryID, UpLevelID) SELECT SectionID, CategoryID, UplevelID FROM @pathtable

	--Rebuild the path (for legacy support, this value is not currently used by the galleries)

	SELECT P.CategoryID, P.[Path] from @pathtable P JOIN cs_Post_Categories C on P.UplevelID = C.CategoryID and C.ParentID = 0

	--Commit the new path to the Categoies table
	UPDATE cs_Post_Categories SET cs_Post_Categories.[Path] = NewPath.[path] from cs_Post_Categories 
		JOIN 
			(SELECT P.CategoryID, P.[Path] FROM @pathtable P 
				JOIN cs_Post_Categories C ON P.UplevelID = C.CategoryID AND C.ParentID = 0
			) NewPath ON cs_Post_Categories.CategoryID = NewPath.CategoryID

END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT  EXECUTE  ON [dbo].[cs_PostCategories_Parents_RebuildIndex]  TO [public]
GO


/***********************************************
* Sproc: cs_PostCategory_CreateUpdateDelete
* File Date: 11/29/2006 10:07:30 AM
***********************************************/
Print 'Creating...cs_PostCategory_CreateUpdateDelete'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_PostCategory_CreateUpdateDelete]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_PostCategory_CreateUpdateDelete]
GO





CREATE PROCEDURE [dbo].[cs_PostCategory_CreateUpdateDelete]
	@DeleteCategory bit=0,
	@SectionID int=0,
	@Name nvarchar(256)='',
	@IsEnabled bit=1,
	@ParentID int=0,
	@Description nvarchar(2000)=null,
	@SettingsID int,
	@FeaturedPostID int = null,
	@CategoryID int=0 out
AS
SET Transaction Isolation Level Read UNCOMMITTED
-- Are we deleting?
if @DeleteCategory = 1
begin
	DELETE FROM cs_Posts_InCategories WHERE CategoryID = @CategoryID
	DELETE FROM [cs_Post_Categories_Parents] WHERE CategoryID = @CategoryID
	DELETE FROM cs_Post_Categories WHERE CategoryID = @CategoryID and SectionID = @SectionID and SettingsID = @SettingsID
	EXEC dbo.cs_PostCategories_Parents_RebuildIndex @SectionID
	RETURN
end

-- Find out the new path
declare @Path nvarchar(255)
set @Path = isnull((select Path + convert(nvarchar, CategoryID) + '/' from cs_Post_Categories where CategoryID = @ParentID and SectionID = @SectionID and SettingsID = @SettingsID), '/')

-- Are we updating?
if @CategoryID > 0
begin
	IF EXISTS (SELECT CategoryID FROM cs_Post_Categories WHERE Name = @Name AND SectionID = @SectionID AND SettingsID = @SettingsID AND CategoryID <> @CategoryID) BEGIN
		SET @CategoryID = -1
		RETURN
	END

	UPDATE cs_Post_Categories SET
		Name = @Name,
		IsEnabled = @IsEnabled,
		ParentID = @ParentID,
		Description = @Description,
		Path = @Path,
		FeaturedPostID = @FeaturedPostID
	WHERE CategoryID = @CategoryID and SectionID = @SectionID and SettingsID = @SettingsID
end
else
begin
	IF EXISTS (SELECT CategoryID FROM cs_Post_Categories WHERE Name = @Name AND SectionID = @SectionID AND SettingsID = @SettingsID) BEGIN
		SET @CategoryID = -1
		RETURN
	END

	INSERT INTO cs_Post_Categories (SectionID, Name, IsEnabled, ParentID, [Description], [Path], SettingsID, FeaturedPostID)
		VALUES (@SectionID, @Name, @IsEnabled, @ParentID, @Description, @Path, @SettingsID, @FeaturedPostID)
	set @CategoryID = SCOPE_IDENTITY()
end
EXEC dbo.cs_PostCategories_Parents_RebuildIndex @SectionID

GO


SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT  EXECUTE  ON [dbo].[cs_PostCategory_CreateUpdateDelete]  TO [public]
GO

/***********************************************
* Sproc: cs_PostMetadata_Get
* File Date: 11/29/2006 10:07:31 AM
***********************************************/
Print 'Creating...cs_PostMetadata_Get'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_PostMetadata_Get]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_PostMetadata_Get]
GO


CREATE PROCEDURE dbo.cs_PostMetadata_Get
	@PostID int,
	@SettingsID int
AS
SET Transaction Isolation Level Read UNCOMMITTED

select MetaKey, MetaType, MetaValue from cs_PostMetadata where PostID = @PostID
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_PostMetadata_Get] to public
go
/***********************************************
* Sproc: cs_PostMetadata_Update
* File Date: 11/29/2006 10:07:31 AM
***********************************************/
Print 'Creating...cs_PostMetadata_Update'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_PostMetadata_Update]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_PostMetadata_Update]
GO


CREATE PROCEDURE dbo.cs_PostMetadata_Update
	@PostID int,
	@MetadataList ntext,
	@SettingsID int
AS
SET Transaction Isolation Level Read UNCOMMITTED
delete from cs_PostMetadata where PostID = @PostID

if @MetadataList is null --or len(ltrim(rtrim(@MetadataList))) = 0
return

declare @idoc int

EXEC sp_xml_preparedocument @idoc OUTPUT, @MetadataList

insert into cs_PostMetaData (PostID, MetaKey, MetaType, MetaValue)
	select @PostID, M.[key], M.[type], M.[value]
	from openxml(@idoc, '/entries/entry', 1)
		with ([key] nvarchar(100), [type] nvarchar(100), [value] nvarchar(100)) as M

EXEC sp_xml_removedocument @idoc
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_PostMetadata_Update] to public
go
/***********************************************
* Sproc: cs_PostPoints_Add
* File Date: 11/29/2006 10:07:31 AM
***********************************************/
Print 'Creating...cs_PostPoints_Add'

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_PostPoints_Add]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_PostPoints_Add]
GO

/***********************************************
* Sproc: cs_posts_AddAuditDeletedPostContent
* File Date: 11/29/2006 10:07:31 AM
***********************************************/
Print 'Creating...cs_posts_AddAuditDeletedPostContent'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_posts_AddAuditDeletedPostContent]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_posts_AddAuditDeletedPostContent]
GO


Create Proc [dbo].cs_posts_AddAuditDeletedPostContent
(
	@PostID int = -1,
	@UserID int  = -1,
	@SectionID int = -1,
	@SettingsID int = -1,
	@ApplicationType int = 9999,
	@ParentID int = -1,
	@ThreadID int = -1,
	@PostType int = -1,
	@PostLevel int = -1,
	@Body ntext = null,
	@Subject nvarchar(500) = null,
	@IPAddress nvarchar(50) = null,
	@PropertyNames ntext = null,
	@PropertyValues ntext = null,
	@SpamScore int = -1,
	@PostStatus int = -1
)

as

Insert cs_posts_deleted_archive (PostID, UserID, SectionID, SettingsID, ApplicationType, Body, Subject, IPAddress, DeletedDate, ParentID, ThreadID, PostLevel, PostType, PropertyNames, PropertyValues, SpamScore, PostStatus)
Values (@PostID, @UserID, @SectionID, @SettingsID, @ApplicationType, @Body, @Subject, @IPAddress, getdate(), @ParentID, @ThreadID, @PostLevel, @PostType, @PropertyNames, @PropertyValues, @SpamScore, @PostStatus)


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT EXECUTE on dbo.cs_posts_AddAuditDeletedPostContent to public
GO
/***********************************************
* Sproc: cs_Posts_GetPostIDByFilter
* File Date: 11/29/2006 10:07:31 AM
***********************************************/
Print 'Creating...cs_Posts_GetPostIDByFilter'

SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS ON
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Posts_GetPostIDByFilter]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Posts_GetPostIDByFilter]
GO
--------------------------------------------------------------------------------
--	cs_Posts_GetPostIDByFilter
--	Returns a list of filtered PostIDs
--------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[cs_Posts_GetPostIDByFilter]
(
	@SettingsID		int,
	@FilterType		int,
	@FilterValue	varchar(255)
)
AS
	SET NOCOUNT ON
	SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED


	-- local variables
	DECLARE	@PostSetSize	int


	IF @FilterType = 1	-- StalePoints
	BEGIN

		-- filter value represent size of post set
		SET @PostSetSize = CONVERT(int, @FilterValue)

		-- limit number of posts to work with (non-positive = ALL)
		IF @PostSetSize > 0
			SET ROWCOUNT @PostSetSize

		-- get posts to work with
		SELECT		P.PostID
		FROM		cs_Posts P
		INNER JOIN	cs_Sections S				-- exclude private messages
			ON		P.SectionID = S.SectionID
		WHERE		P.SettingsID = @SettingsID
			AND		S.EnablePostPoints = 1		-- ignore excluded sections
			AND		P.IsApproved = 1			-- ignore posts awaiting moderation
		ORDER BY	P.PointsUpdated				-- start with "stalest" posts

		-- limit has been used; reset to default
		IF @PostSetSize > 0
			SET ROWCOUNT 0
	END


	RETURN
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO

GRANT EXECUTE on [dbo].[cs_Posts_GetPostIDByFilter] to [public]

/***********************************************
* Sproc: cs_Posts_GetPostInCategories
* File Date: 11/29/2006 10:07:29 AM
***********************************************/
Print 'Creating...cs_Posts_GetPostInCategories'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Posts_GetPostInCategories]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Posts_GetPostInCategories]
GO





CREATE PROCEDURE dbo.cs_Posts_GetPostInCategories
	@PostID int
AS

SET Transaction Isolation Level Read UNCOMMITTED

SELECT
	C.*
FROM cs_Posts_InCategories P
RIGHT JOIN cs_Post_Categories C ON C.CategoryID = P.CategoryID
WHERE P.PostID = @PostID
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT  EXECUTE  ON [dbo].[cs_Posts_GetPostInCategories]  TO [public]
GO

/***********************************************
* Sproc: cs_Posts_GetPostsInNoCategories
* File Date: 11/29/2006 10:07:31 AM
***********************************************/
Print 'Creating...cs_Posts_GetPostsInNoCategories'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Posts_GetPostsInNoCategories]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Posts_GetPostsInNoCategories]
GO





CREATE PROCEDURE dbo.cs_Posts_GetPostsInNoCategories
	@SectionID int
AS
SET Transaction Isolation Level Read UNCOMMITTED
SELECT
	P.PostID, P.ThreadID, P.ParentID, P.PostAuthor, P.UserID, P.SectionID, P.PostLevel, P.SortOrder, P.Subject, P.PostDate, P.IsApproved,
	P.IsLocked, P.IsIndexed, P.TotalViews, P.Body, P.FormattedBody, P.IPAddress, P.PostType, P.EmoticonID, P.SettingsID, P.AggViews,
	P.PropertyNames as PostPropertyNames, P.PropertyValues as PostPropertyValues
FROM cs_Posts P
WHERE P.SectionID = @SectionID
	AND P.ParentID = P.PostID
	AND P.PostID NOT IN ( SELECT PostID FROm cs_Posts_InCategories )
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT  EXECUTE  ON [dbo].[cs_Posts_GetPostsInNoCategories]  TO [public]
GO

/***********************************************
* Sproc: cs_Posts_ReindexBySection
* File Date: 11/29/2006 10:07:31 AM
***********************************************/
Print 'Creating...cs_Posts_ReindexBySection'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Posts_ReindexBySection]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Posts_ReindexBySection]
GO


CREATE PROCEDURE [dbo].[cs_Posts_ReindexBySection]
(
	@SectionID	int,
	@SettingsID	int
)
AS
	--this proc intentionally renames all posts across all settingsids by that user


	-- first, set the post to be removed from the index
	INSERT cs_es_Search_RemoveQueue (PostID, SettingsID) 
	SELECT P.PostID, P.SettingsID 
	FROM cs_Posts P 
	WHERE P.SectionID = @SectionID AND P.SettingsID = @SettingsID
	AND	PostID NOT IN (SELECT PostID FROM cs_es_Search_RemoveQueue)

	-- step 2, add post to reindex table
	UPDATE cs_Posts set IsIndexed = 0 
	FROM cs_Posts P 
	WHERE P.SectionID = @SectionID AND P.SettingsID = @SettingsID
GO


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_Posts_ReindexBySection] to public
go
/***********************************************
* Sproc: cs_Posts_ReindexByTag
* File Date: 11/29/2006 10:07:33 AM
***********************************************/
Print 'Creating...cs_Posts_ReindexByTag'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Posts_ReindexByTag]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Posts_ReindexByTag]
GO


CREATE PROCEDURE [dbo].[cs_Posts_ReindexByTag]
(
	@CategoryID	int,
	@SettingsID	int
)
AS
	-- first, set the post to be removed from the index
	INSERT cs_es_Search_RemoveQueue (PostID, SettingsID) 
	SELECT P.PostID, P.SettingsID 
	FROM cs_Posts P 
		JOIN cs_Posts_InCategories PIC on P.PostID = PIC.PostID 
	WHERE PIC.CategoryID = @CategoryID AND P.SettingsID = @SettingsID
	AND	P.PostID NOT IN (SELECT PostID FROM cs_es_Search_RemoveQueue)

	-- step 2, reset post to be indexed
	UPDATE cs_Posts set IsIndexed = 0 
	From cs_Posts P 
		JOIN cs_Posts_InCategories PIC on P.PostID = PIC.PostID 
	WHERE PIC.CategoryID = @CategoryID AND P.SettingsID = @SettingsID
GO


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_Posts_ReindexByTag] to public
go
/***********************************************
* Sproc: cs_Posts_ReindexByUser
* File Date: 11/29/2006 10:07:31 AM
***********************************************/
Print 'Creating...cs_Posts_ReindexByUser'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Posts_ReindexByUser]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Posts_ReindexByUser]
GO


CREATE PROCEDURE [dbo].[cs_Posts_ReindexByUser]
(
	@UserID	int
)
AS
	--this proc intentionally renames all posts across all settingsids by that user


	-- first, set the post to be removed from the index
	INSERT INTO	cs_es_Search_RemoveQueue (PostID, SettingsID)
	SELECT		PostID, SettingsID
	FROM		cs_Posts
	WHERE		UserID = @UserID
		AND	PostID NOT IN (SELECT PostID FROM cs_es_Search_RemoveQueue)

	-- step 2, add post to reindex table
	UPDATE	cs_Posts
	SET		IsIndexed =  0
	WHERE	UserID = @UserID
GO


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_Posts_ReindexByUser] to public
go
/***********************************************
* Sproc: cs_Posts_UpdatePostsInCategories
* File Date: 11/29/2006 10:07:33 AM
***********************************************/
Print 'Creating...cs_Posts_UpdatePostsInCategories'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Posts_UpdatePostsInCategories]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Posts_UpdatePostsInCategories]
GO

CREATE  Proc [dbo].cs_Posts_UpdatePostsInCategories
(
	@CategoryList nvarchar(4000) = null,
	@SectionID int,
	@PostID int,
	@SettingsID int = null,
	@UpdateStats bit = 1
)
as

DELETE FROM cs_Posts_InCategories where PostID = @PostID

-- If the post is not in any categories, we have to rebuild the index incase we are deleting a post or removing categories
IF @CategoryList Is Not Null AND LEN(LTRIM(RTRIM(@CategoryList))) > 0
BEGIN
	DECLARE @idoc int
	-- declare @CategoryList nvarchar(4000)
	-- select @CategoryList = "<?xml version=""1.0"" ?><Categories><Category>Test</Category></Categories>"

	EXEC sp_xml_preparedocument @idoc OUTPUT, @CategoryList

	DECLARE @CategoryIDList TABLE
	(
		CategoryID Int
	)

	--Insert Missing Categories
	INSERT INTO cs_Post_Categories (SectionID, [Name], IsEnabled, ParentID, [Description], SettingsID)
		Select 	DISTINCT
			@SectionID, CONVERT(nvarchar(255), X.[text]), 1, 0, null, @SettingsID
		FROM 
			OPENXML(@idoc, '/Categories/Category/', 2) X
		where 
			X.[text] is not null  
			and CONVERT(nvarchar(255), X.[text]) not in (
				Select [Name] FROM cs_Post_Categories where SectionID = @SectionID
			) 
	IF @@ROWCOUNT > 0
		exec [cs_PostCategories_Parents_RebuildIndex] @SectionID

	Insert Into @CategoryIDList (CategoryID) 
	SELECT DISTINCT C.CategoryID 
		FROM OPENXML(@idoc, '/Categories/Category/', 2) X
		inner join cs_Post_Categories C on C.[Name] = Convert(nvarchar(256),X.[text]) collate database_default
				and C.SectionID = @SectionID

		--Insert Entry Categories
		INSERT INTO cs_Posts_InCategories 
			( PostID, CategoryID, SettingsID)
		Select 
			@PostID, C.CategoryID, @SettingsID
		FROM 
			@CategoryIDList C
	
	EXEC sp_xml_removedocument @idoc
END

if(@UpdateStats = 1) --for changes we need to rebuild the entire section stats
Begin
	UPDATE cs_Post_Categories SET
		TotalSubThreads = IsNull(QSUB.posts, 0),
		MostRecentSubPostDate = QSUB.postdate,
		TotalThreads = IsNull(QCURR.posts, 0),
		MostRecentPostDate = QCURR.postdate
	FROM cs_Post_Categories 
	LEFT  JOIN (
	SELECT P.UplevelID CategoryID, COUNT(PIC.PostID) posts, MAX(jP.PostDate) postdate 
	FROM 
		cs_Posts_InCategories PIC 
		INNER JOIN cs_Posts jP ON (jP.PostID = PIC.PostID AND jP.PostID = jP.ParentID) 
		INNER JOIN cs_Post_Categories_Parents P ON PIC.CategoryID = P.CategoryID and P.SectionID = @SectionID
		INNER JOIN cs_Post_Categories C ON C.CategoryID = P.CategoryID
	WHERE jP.IsApproved = 1
	GROUP BY P.UpLevelID
	) QSUB ON cs_Post_Categories.CategoryID = QSUB.CategoryID

	LEFT  JOIN (
	SELECT C.CategoryID CategoryID, COUNT(PIC.PostID) posts, MAX(jP.PostDate) postdate 
	FROM 
		cs_Posts_InCategories PIC 
		INNER JOIN cs_Posts jP ON (jP.PostID = PIC.PostID AND jP.PostID = jP.ParentID) 
		INNER JOIN cs_Post_Categories C ON C.CategoryID = PIC.CategoryID
	WHERE jP.IsApproved = 1
	GROUP BY C.CategoryID
	) QCURR ON cs_Post_Categories.CategoryID = QCURR.CategoryID
	WHERE cs_Post_Categories.SectionID = @SectionID
End

if(@UpdateStats = 3) --this code is only good for additions
Begin

	UPDATE cs_Post_Categories SET
		TotalSubThreads = QSUB.posts,
		MostRecentSubPostDate = QSUB.postdate,
		TotalThreads = QCURR.posts,
		MostRecentPostDate = QCURR.postdate
	FROM cs_Post_Categories JOIN
	(
	SELECT P.UplevelID CategoryID, COUNT(PIC.PostID) posts, MAX(jP.PostDate) postdate 
	FROM 
		@CategoryIDList cid
		inner join cs_Post_Categories C on C.CategoryID = cid.CategoryID
		Inner Join cs_Post_Categories_Parents P on C.CategoryID = P.CategoryID
		INNER JOIN cs_Posts_InCategories PIC on PIC.CategoryID = P.CategoryID
		INNER JOIN cs_Posts jP ON (jP.PostID = PIC.PostID AND jP.PostID = jP.ParentID) 
	WHERE jP.IsApproved = 1
		Group By P.UplevelID
	) QSUB on cs_Post_Categories.CategoryID = QSUB.CategoryID

	JOIN
	(
	SELECT C.CategoryID CategoryID, COUNT(PIC.PostID) posts, MAX(jP.PostDate) postdate 
	FROM 
		@CategoryIDList cid
		inner join cs_Post_Categories C on C.CategoryID = cid.CategoryID
		INNER JOIN cs_Posts_InCategories PIC on C.CategoryID  =  PIC.CategoryID
		INNER JOIN cs_Posts jP ON (jP.PostID = PIC.PostID AND jP.PostID = jP.ParentID)
	WHERE jP.IsApproved = 1
		Group By C.CategoryID
	) QCURR on cs_Post_Categories.CategoryID = QCURR.CategoryID

End


/* This code has been replaced by the update statements above DanB 7-19-2005 */
if(@UpdateStats = 2)
Begin

	-- Update the most recent post dates and total thread stuff for the categories
	declare @UpCategoryID int
	declare @UpPath nvarchar(256)
	DECLARE Categories_Cursor CURSOR FOR
		SELECT CategoryID FROM cs_Post_Categories WHERE SectionID = @SectionID
	
	OPEN Categories_Cursor
	FETCH NEXT FROM Categories_Cursor INTO @UpCategoryID
	
	WHILE @@FETCH_STATUS = 0
	BEGIN
	
		set @UpPath = (select Path from cs_Post_Categories where CategoryID = @UpCategoryID)
	
		UPDATE cs_Post_Categories SET
			TotalThreads = IsNull((SELECT COUNT(PIC.PostID) FROM cs_Posts_InCategories PIC INNER JOIN cs_Posts jP ON (jP.PostID = PIC.PostID AND jP.PostID = jP.ParentID) WHERE PIC.CategoryID = @UpCategoryID AND jP.IsApproved = 1), 0),
			TotalSubThreads = IsNull((SELECT COUNT(P.PostID) FROM cs_Posts P INNER JOIN cs_Post_Categories jC ON (jC.CategoryID = @UpCategoryID OR jC.Path LIKE @UpPath + convert(nvarchar, @UpCategoryID) + '/%') INNER JOIN cs_Posts_InCategories jPIC ON (jPIC.CategoryID = jC.CategoryID) WHERE P.PostID = P.ParentID AND P.PostID = jPIC.PostID AND P.IsApproved = 1), 0),
			MostRecentPostDate = (SELECT MAX(PostDate) FROM cs_Posts_InCategories PIC INNER JOIN cs_Posts jP ON (jP.PostID = PIC.PostID AND jP.PostID = jP.ParentID) WHERE PIC.CategoryID = @UpCategoryID and jP.IsApproved = 1),
			MostRecentSubPostDate = (SELECT MAX(PostDate) FROM cs_Posts P INNER JOIN cs_Post_Categories jC ON (jC.CategoryID = @UpCategoryID OR jC.Path LIKE @UpPath + convert(nvarchar, @UpCategoryID) + '/%') INNER JOIN cs_Posts_InCategories jPIC ON (jPIC.CategoryID = jC.CategoryID) WHERE P.PostID = P.ParentID AND P.PostID = jPIC.PostID AND P.IsApproved = 1)
		WHERE CategoryID = @UpCategoryID
	
		FETCH NEXT FROM Categories_Cursor INTO @UpCategoryID
	END
	
	CLOSE Categories_Cursor
	DEALLOCATE Categories_Cursor
	
END

GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_Posts_UpdatePostsInCategories] to public
go

/***********************************************
* Sproc: cs_Posts_Views_Add
* File Date: 11/29/2006 10:07:31 AM
***********************************************/
Print 'Creating...cs_Posts_Views_Add'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Posts_Views_Add]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Posts_Views_Add]
GO

Create Proc [dbo].cs_Posts_Views_Add
(
	@PostID int,
	@AggCount int,
	@WebCount int
)

as
SET Transaction Isolation Level Read UNCOMMITTED

Update cs_Posts
Set 
	TotalViews = TotalViews + @WebCount,
	AggViews = AggViews + @AggCount
Where 
	PostID = @PostID

declare @ThreadID int
set @ThreadID = (select ThreadID from cs_Posts where PostID = @PostID)

update cs_Threads
set
	TotalViews = TotalViews + @WebCount
where
	ThreadID = @ThreadID

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_Posts_Views_Add] to public
go
/***********************************************
* Sproc: cs_Post_CreateUpdate
* File Date: 11/29/2006 10:07:31 AM
***********************************************/
Print 'Creating...cs_Post_CreateUpdate'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Post_CreateUpdate]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Post_CreateUpdate]
GO




CREATE  PROCEDURE [dbo].cs_Post_CreateUpdate
(
	@SectionID int,
	@ParentID int,
	@AllowDuplicatePosts bit,
	@DuplicateIntervalInMinutes int = 0,
	@Subject nvarchar(256),
 	@UserID int,
	@PostAuthor nvarchar(64) = null,
	@Body ntext,
	@FormattedBody ntext,
	@EmoticonID int = 0,
	@IsLocked bit,
	@IsSticky bit,
	@IsApproved bit,
	@StickyDate datetime,
	@PostType int = 0,
	@PostMedia int = 0,
	@PostDate datetime = null,
	@UserHostAddress nvarchar(32),
	@PropertyNames ntext = null,
	@PropertyValues ntext = null,
	@SettingsID int, 
	@IsTracked bit = 0,
	@PostID int out,
	@ThreadID int=0 out,
	@PostConfiguration int = 0,
	@UpdateSectionStatistics bit = 1,
	@UserTime datetime = null,
	@ApplicationPostType int,
	@PostName nvarchar(256) =  null,
	@ThreadStatus int = 0,
	@Points int = 0,
	@PostDisplayName nvarchar(64) = null,
	@AutoApprove bit = 0
) 
AS
/*
	stored procedure cs_Post_CreateUpdate
	* Procedure now creates new threads here, from an identity column in cs_Threads.
	* To update a Post, ParentID must not equal 0.
	* To delete a post, use forums_Moderate_Posts_Move to move it to the Deleted Forum
  * Default value for ThreadStatus is Not Set (0)
*/

SET NOCOUNT ON
DECLARE @MaxSortOrder int
DECLARE @ParentLevel int
DECLARE @ParentSortOrder int
DECLARE @NextSortOrder int
DECLARE @ModeratedForum bit
DECLARE @EnablePostStatistics bit
DECLARE @TrackThread bit
DECLARE @ContextUserID int
DECLARE @ContextPostAuthor nvarchar(64)

-- Set 'not set' for Sticky and Anouncement posts
IF ((@IsSticky = 1) OR ((@IsLocked = 1) AND ( @StickyDate > DATEADD( Year, 2, getdate() ) )))
	SET @ThreadStatus = 0 -- not set value

-- set the PostDate
IF @PostDate IS NULL
	SET @PostDate = GetDate()

IF @UserTime IS NULL
	SET @UserTime = GetDate()

-- Get the real username for poster
IF @PostAuthor IS NULL
	SELECT 
		@PostAuthor = UserName
	FROM 
		cs_vw_Users_FullUser  
	WHERE 
		cs_UserID = @UserID and SettingsID = @SettingsID

-- Check if this is an anonymous post (value = 1)
IF (@PostConfiguration & 1) = 1
BEGIN
	-- Anonymous ID
	SELECT @ContextUserID = cs_UserID FROM cs_vw_Users_FullUser WHERE SettingsID = @SettingsID and IsAnonymous = 1

	-- Set the username
	IF(@PostAuthor is not null)
	begin
		SET @ContextPostAuthor = @PostAuthor
	end
	else
	begin
		SET @ContextPostAuthor = ''
	end
END
ELSE
BEGIN
	-- Set the real user ID
	SET @ContextUserID = @UserID

	IF(@PostDisplayName is not null)
	Begin
		-- Set the real username
		SET @ContextPostAuthor = @PostDisplayName
	END
	ELSE
	BEGIN
		SET @ContextPostAuthor = @PostAuthor
	END
END

-- Do we care about duplicates?
IF @AllowDuplicatePosts = 0
BEGIN
	DECLARE @IsDuplicate bit
	exec cs_system_DuplicatePost @UserID, @Body, @DuplicateIntervalInMinutes, @SettingsID, @IsDuplicate output

	IF @IsDuplicate = 1
	BEGIN
		SET @PostID = -1	
		RETURN	-- Exit with error code.
	END
END

-- we need to get the SectionID, if the ParentID is not null (there should be a SectionID)
IF @SectionID = 0 AND @ParentID <> 0
	SELECT 
		@SectionID = SectionID
	FROM 
		cs_Posts (nolock) 
	WHERE 
		PostID = @ParentID and SettingsID = @SettingsID

-- Is this forum moderated?
SELECT 
	@ModeratedForum = IsModerated, @EnablePostStatistics = EnablePostStatistics
FROM 
	cs_Sections (nolock)
WHERE 
	SectionID = @SectionID and SettingsID = @SettingsID

-- Determine if this post will be approved.
-- If the forum is NOT moderated, then the post will be approved by default.
SET NOCOUNT ON
BEGIN TRAN

IF @AutoApprove = 1
BEGIN
	SET @IsApproved = 1
END
ELSE IF @IsApproved = 1 AND @ModeratedForum = 1 AND @SectionID <> 0
BEGIN
	-- ok, this is a moderated forum.  Is this user trusted?  If he is, then the post is approved ; else it is not
	SET @IsApproved = ( 
		SELECT
			ModerationLevel
		FROM
			cs_UserProfile (nolock)
		WHERE
			UserID = @UserID and SettingsID = @SettingsID )
END


-- EAD: Modifying this sproc to insert directly into cs_Threads.  We are no longer keying
-- cs_Threads.ThreadID to be same number as the top PostID for the thread.  This is to allow
-- for the FKs to be put into place.

IF @ParentID = 0	-- parameter indicating this is a top-level post (for a new thread)
BEGIN
	-- First we create a new ThreadID.

	-- check the StickyDate to ensure it's not null
	IF @StickyDate < @PostDate
		SET @StickyDate = @PostDate

	INSERT cs_Threads 	
		( SectionID,
		PostDate, 
		UserID, 
		PostAuthor, 
		ThreadDate, 
		MostRecentPostAuthor, 
		MostRecentPostAuthorID, 	
		MostRecentPostID,
		IsLocked, 
		IsApproved,
		IsSticky, 
		StickyDate, 
		ThreadEmoticonID,
		SettingsID,
		ThreadStatus )
	VALUES
		( @SectionID, 
		@PostDate, 
		@UserID, 
		@PostAuthor,
		@PostDate,
		@ContextPostAuthor,
		@ContextUserID, 
		0,	-- MostRecentPostID, which we don't know until after post INSERT below.
		@IsLocked,
		@IsApproved,
		@IsSticky,
		@StickyDate,
		@EmoticonID,
		@SettingsID,
		@ThreadStatus )

	-- Get the new ThreadID
	SELECT 
		@ThreadID = @@IDENTITY
	--FROM
		--cs_Threads
		
	-- Now we add the new post
	INSERT cs_Posts 
		( SectionID, 
		ThreadID, 
		ParentID, 
		PostLevel, 
		SortOrder, 
		Subject, 
		UserID, 
		PostAuthor, 
		IsApproved, 
		IsLocked, 

		Body, 

		FormattedBody, 
		PostType, 
		PostMedia,
		PostDate, 
		IPAddress, 
		EmoticonID,
		PropertyNames,
		PropertyValues,
		SettingsID,
		PostConfiguration,
		UserTime,
		PostName,
		ApplicationPostType,
		Points )
	VALUES 
		( @SectionID, 
		@ThreadID, 
		0, 	-- ParentID, which we don't know until after INSERT
		1, 	-- PostLevel, 1 marks start/top/first post in thread.
		1, 	-- SortOrder (not in use at this time)
		@Subject, 
		@UserID, 
		@PostAuthor,
		@IsApproved, 
		@IsLocked, 
		@Body, 
		@FormattedBody, 
		@PostType, 
		@PostMedia, 
		@PostDate, 
		@UserHostAddress, 
		@EmoticonID,
		@PropertyNames,
		@PropertyValues,
		@SettingsID,
		@PostConfiguration,
		@UserTime,
		@PostName,
		@ApplicationPostType,
		@Points )
		

	-- Get the new PostID
	SELECT 
		@PostID = @@IDENTITY
--	FROM
--		cs_Posts

	-- Update the new Thread with the new PostID
	UPDATE 
		cs_Threads
	SET 
		MostRecentPostID = @PostID
	WHERE 
		ThreadID = @ThreadID and SettingsID = @SettingsID

	-- Update the new Post's ParentID with the new PostID
	UPDATE 
		cs_Posts
	SET 
		ParentID = @PostID
	WHERE 
		PostID = @PostID and SettingsID = @SettingsID

END
ELSE BEGIN	-- @ParentID <> 0 means there is a reply to an existing post

	-- Get the Post Information for what we are replying to
	SELECT 
		@ThreadID = ThreadID,
		@SectionID = SectionID,
		@ParentLevel = PostLevel,
		@ParentSortOrder = SortOrder
	FROM 
		cs_Posts
	WHERE 
		PostID = @ParentID and SettingsID = @SettingsID

	-- Is there another post at the same level or higher?
	SET @NextSortOrder = (
		SELECT 	
			MIN(SortOrder) 
		FROM 
			cs_Posts 
		WHERE 
			PostLevel <= @ParentLevel 
			AND SortOrder > @ParentSortOrder 
			AND ThreadID = @ThreadID  and SettingsID = @SettingsID )

	IF @NextSortOrder > 0
	BEGIN
		-- Move the existing posts down
		UPDATE 
			cs_Posts
		SET 
			SortOrder = SortOrder + 1
		WHERE 
			ThreadID = @ThreadID
			AND SortOrder >= @NextSortOrder and SettingsID = @SettingsID

		SET @MaxSortOrder = @NextSortOrder

	END
   	ELSE BEGIN 	-- There are no posts at this level or above
	
		-- Find the highest sort order for this parent
		SELECT 
			@MaxSortOrder = MAX(SortOrder) + 1
		FROM 
			cs_Posts
		WHERE 
			ThreadID = @ThreadID and SettingsID = @SettingsID

	END 

	-- Insert the new post
	INSERT cs_Posts 
		( SectionID, 
		ThreadID, 
		ParentID, 
		PostLevel, 
		SortOrder, 
		Subject, 
		UserID, 
		PostAuthor, 
		IsApproved, 
		IsLocked, 
		Body, 
		FormattedBody, 
		PostType, 
		PostMedia, 
		PostDate, 
		IPAddress, 
		EmoticonID,
		PropertyNames,
		PropertyValues,
		SettingsID,
		PostConfiguration,
		UserTime,
		PostName,
		ApplicationPostType,
		Points )
	VALUES 
		( @SectionID, 
		@ThreadID, 
		@ParentID, 
		@ParentLevel + 1, 
		@MaxSortOrder,
		@Subject, 
		@UserID, 
		@PostAuthor, 
		@IsApproved, 
		@IsLocked, 
		@Body, 
		@FormattedBody, 
		@PostType, 
		@PostMedia, 
		@PostDate, 
		@UserHostAddress, 
		@EmoticonID,
		@PropertyNames,
		@PropertyValues,
		@SettingsID,
		@PostConfiguration,
		@UserTime,
		@PostName,
		@ApplicationPostType,
		@Points )


	-- Now check to see if this post is Approved by default.
	-- If so, we go ahead and update the Threads table for the MostRecent items.
	IF @IsApproved = 1
	BEGIN		
		-- Grab the new PostID and update the ThreadID's info
		SELECT 
			@PostID = @@IDENTITY 
--		FROM 
--			cs_Posts

		-- To cut down on overhead, I've elected to update the thread's info
		-- directly from here, without running cs_system_UpdateThread since
		-- I already have all of the information that this sproc would normally have to lookup.
		Select @StickyDate = StickyDate FROM cs_Threads where ThreadID = @ThreadID and SettingsID = @SettingsID

		IF @StickyDate < @PostDate
			SET @StickyDate = @PostDate

		UPDATE
			cs_Threads 	
		SET 
			MostRecentPostAuthor = @ContextPostAuthor,
			MostRecentPostAuthorID = @ContextUserID,
			MostRecentPostID = @PostID,
			TotalReplies = TotalReplies + 1, -- (SELECT COUNT(*) FROM cs_Posts WHERE ThreadID = @ThreadID AND IsApproved = 1 AND PostLevel > 1),
			IsLocked = @IsLocked,
			StickyDate = @StickyDate,	-- this makes the thread a sticky/announcement, even if it's a reply.
			ThreadDate = @PostDate
		WHERE
			ThreadID = @ThreadID and SettingsID = @SettingsID
	END
	ELSE
	BEGIN
		-- Moderated Posts: get the new PostID
		SELECT @PostID = @@IDENTITY 
	END

	-- Clean up ThreadsRead (this should work very well now)
	DELETE
		cs_ThreadsRead
	WHERE
		ThreadID = @ThreadID 
		AND UserID != @UserID and SettingsID = @SettingsID
END


-- Update the users tracking for the new post (if needed)
SELECT 
	@TrackThread = EnableThreadTracking 
FROM 
	cs_UserProfile (nolock) 
WHERE 
	UserID = @UserID and SettingsID = @SettingsID

IF @TrackThread = 1 and @IsTracked = 1
	-- If a row already exists to track this thread for this user, do nothing - otherwise add the row
	IF NOT EXISTS ( SELECT ThreadID FROM cs_TrackedThreads (nolock) WHERE ThreadID = @ThreadID AND UserID = @UserID  and SettingsID = @SettingsID)
		INSERT INTO cs_TrackedThreads 
			( ThreadID, UserID, SettingsID)
		VALUES
			( @ThreadID, @UserID, @SettingsID )

COMMIT TRAN
BEGIN TRAN

-- Is this a private post
IF @SectionID = 0
	EXEC cs_PrivateMessages_CreateDelete @UserID, @ThreadID, @SettingsID, 0

-- Update the forum statitics
IF @SectionID > 0 AND @UserID > 0
BEGIN
	IF @IsApproved = 1 AND @EnablePostStatistics = 1
	BEGIN
		EXEC cs_system_UpdateUserPostCount @SectionID, @UserID, @SettingsID
	END

	IF @UpdateSectionStatistics = 1
	BEGIN
		EXEC cs_system_UpdateForum @SectionID, @ThreadID, @PostID, @SettingsID, 1, @PostDisplayName
	END
END


COMMIT TRAN
SET NOCOUNT OFF

SELECT @PostID = @PostID



GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT  EXECUTE  ON [dbo].[cs_Post_CreateUpdate]  TO [public]
GO


/***********************************************
* Sproc: cs_Post_Delete
* File Date: 11/29/2006 10:07:30 AM
***********************************************/
Print 'Creating...cs_Post_Delete'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO


if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Post_Delete]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Post_Delete]
GO

CREATE PROCEDURE dbo.cs_Post_Delete
(
	@SectionID int,
	@SettingsID int,
	@PostID int,
	@ResetStatistics bit = 1,
	@DeletedBy INT,
	@Reason NVARCHAR(1024) = ''
)
AS
-- Permanently deletes one post at a time and eventually its thread.
-- If the post has some replies then subsequent calls are made till all the tree's nodes and leafs are removed.
-- Also if the post is level 1 then we can delete the thread itself without any other checkings.

SET Transaction Isolation Level Read UNCOMMITTED
BEGIN

DECLARE @PostLevel INT
DECLARE @ThreadID INT
DECLARE @HasReplies INT

-- Figure out if this is a thread starter post, who is its thread and if it has some replies
--------------------------------------------------------------------------------
SELECT 
	@PostLevel = PostLevel,
	@ThreadID = ThreadID	
FROM 
	cs_Posts 
WHERE 
	PostID = @PostID AND
	SectionID = @SectionID AND
	SettingsID = @SettingsID

SET @HasReplies = (SELECT COUNT(*) FROM cs_Posts WHERE ParentID = @PostID AND SectionID = @SectionID AND SettingsID = @SettingsID)
--------------------------------------------------------------------------------

-- Is a starter thread post?
IF (@PostLevel = 1)
BEGIN
	-- Easy job: delete the thread and its content with statistics update
	--------------------------------------------------------------------------------
	EXEC cs_Thread_Delete @SettingsID, @SectionID, @ThreadID, @ResetStatistics, @DeletedBy, ''

	RETURN 1
	--------------------------------------------------------------------------------
END
ELSE
BEGIN
	-- This is not a thread starter post, so we have to delete it carefully

	-- Delete parent post
	--------------------------------------------------------------------------------	
	DELETE FROM cs_PostAttachments WHERE PostID = @PostID AND SettingsID = @SettingsID
	
	DELETE FROM cs_PostEditNotes WHERE PostID = @PostID AND SettingsID = @SettingsID
	
	DELETE FROM cs_Posts_InCategories WHERE PostID = @PostID AND SettingsID = @SettingsID
		
	DELETE FROM cs_PostsArchive WHERE PostID = @PostID AND SettingsID = @SettingsID
	
	DELETE FROM cs_SearchBarrel WHERE SectionID = @SectionID  AND ThreadID = @ThreadID AND PostID = @PostID AND SettingsID = @SettingsID
	
	DELETE FROM cs_Posts WHERE PostID = @PostID AND ThreadID = @ThreadID AND SectionID = @SectionID AND SettingsID = @SettingsID
	
	IF (@Reason IS NULL OR @Reason = '')
		SET @Reason = 'Automatic generated reason: the post has been permanently deleted on request.'

	EXEC cs_system_ModerationAction_AuditEntry 4, @DeletedBy, @PostID, null, null, @SettingsID, @Reason	
	--------------------------------------------------------------------------------	

	-- Do we have some replies?
	--------------------------------------------------------------------------------	
	IF (@HasReplies > 0)
	BEGIN
		-- There should be some replies/children bound to this post.
		-- Get replying posts one by one through a local cursor and call its removal.

		DECLARE @CurrentPostID INT

		DECLARE Posts_Cursor CURSOR LOCAL FORWARD_ONLY FOR
		SELECT 
			PostID 
		FROM
			cs_Posts
		WHERE
			ParentID = @PostID AND
			ThreadID = @ThreadID AND
			SectionID = @SectionID AND
			SettingsID = @SettingsID

		OPEN Posts_Cursor
		
		FETCH NEXT FROM Posts_Cursor INTO @CurrentPostID

		WHILE (@@FETCH_STATUS = 0)
		BEGIN
			-- Recursively call with no statistics update
			EXEC cs_Post_Delete @SectionID, @SettingsID, @CurrentPostID, 0, @DeletedBy, @Reason

			FETCH NEXT FROM Posts_Cursor INTO @CurrentPostID
		END

		CLOSE Posts_Cursor

		DEALLOCATE Posts_Cursor		
	END
	--------------------------------------------------------------------------------	
	
	-- Update statistics?
	--------------------------------------------------------------------------------	
	IF (@ResetStatistics = 1)
	BEGIN
		EXEC cs_system_ResetThreadStatistics @ThreadID
		EXEC cs_system_ResetForumStatistics @SectionID
	END
	--------------------------------------------------------------------------------	

	RETURN 1
END

END
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO


grant execute on [dbo].[cs_Post_Delete] to public
go
/***********************************************
* Sproc: cs_Post_GetAuthorID
* File Date: 11/29/2006 10:07:31 AM
***********************************************/
Print 'Creating...cs_Post_GetAuthorID'

SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS ON
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Post_GetAuthorID]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Post_GetAuthorID]
GO
--------------------------------------------------------------------------------
--	cs_Post_GetAuthorID
--	Returns a post author's userID
--------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[cs_Post_GetAuthorID]
(
	@SettingsID	int,
	@PostID		int,
	@UserID		int	OUTPUT
)
AS
	SET NOCOUNT ON
	SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED


	-- lookup author for post
	SELECT	@UserID = P.UserID
	FROM	cs_Posts P
	WHERE	P.PostID = @PostID
		AND	P.SettingsID = @SettingsID


	RETURN
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO

GRANT EXECUTE on [dbo].[cs_Post_GetAuthorID] to [public]

/***********************************************
* Sproc: cs_Post_GetPageIndex
* File Date: 11/29/2006 10:07:31 AM
***********************************************/
Print 'Creating...cs_Post_GetPageIndex'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Post_GetPageIndex]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Post_GetPageIndex]
GO



CREATE   PROCEDURE dbo.cs_Post_GetPageIndex
(
	@PostID int,
	@PageSize int,
	@SortBy int,
	@SortOrder bit,
	@AllowUnapproved bit = 0,
	@SettingsID int
)
AS

DECLARE @ThreadID int
SELECT @ThreadID = ThreadID FROM cs_Posts WHERE PostID = @PostID AND SettingsID = @SettingsID

-- Create a temp table to store the select results
CREATE TABLE #PageIndex 
(
	IndexID int IDENTITY (0, 1) NOT NULL,
	PostID int
)

-- Sort by Post Date
IF @SortBy = 0 AND @SortOrder = 0
    INSERT INTO #PageIndex (PostID)
    SELECT PostID FROM cs_Posts (nolock) WHERE (IsApproved = 1 OR 1 = @AllowUnapproved) AND ThreadID = @ThreadID and SettingsID = @SettingsID ORDER BY PostDate

ELSE IF @SortBy = 0 AND @SortOrder = 1
    INSERT INTO #PageIndex (PostID)
    SELECT PostID FROM cs_Posts (nolock) WHERE (IsApproved = 1 OR 1 = @AllowUnapproved) AND ThreadID = @ThreadID and SettingsID = @SettingsID  ORDER BY PostDate DESC

-- Sort by Author
IF @SortBy = 1 AND @SortOrder = 0
    INSERT INTO #PageIndex (PostID)
    SELECT PostID FROM cs_Posts (nolock) WHERE (IsApproved = 1 OR 1 = @AllowUnapproved) AND ThreadID = @ThreadID and SettingsID = @SettingsID  ORDER BY UserID

ELSE IF @SortBy = 1 AND @SortOrder = 1
    INSERT INTO #PageIndex (PostID)
    SELECT PostID FROM cs_Posts (nolock) WHERE (IsApproved = 1 OR 1 = @AllowUnapproved) AND ThreadID = @ThreadID and SettingsID = @SettingsID  ORDER BY UserID DESC

-- Sort by SortOrder
IF @SortBy = 2 AND @SortOrder = 0
    INSERT INTO #PageIndex (PostID)
    SELECT PostID FROM cs_Posts (nolock) WHERE (IsApproved = 1 OR 1 = @AllowUnapproved) AND ThreadID = @ThreadID and SettingsID = @SettingsID  ORDER BY SortOrder

ELSE IF @SortBy = 2 AND @SortOrder = 1
    INSERT INTO #PageIndex (PostID)
    SELECT PostID FROM cs_Posts (nolock) WHERE (IsApproved = 1 OR 1 = @AllowUnapproved) AND ThreadID = @ThreadID and SettingsID = @SettingsID  ORDER BY SortOrder DESC

SELECT (IndexID / @PageSize) + 1 AS PageIndex FROM #PageIndex WHERE PostID = @PostID




GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_Post_GetPageIndex] to public
go

/***********************************************
* Sproc: cs_Post_GetRandomPostID
* File Date: 11/29/2006 10:07:30 AM
***********************************************/
Print 'Creating...cs_Post_GetRandomPostID'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Post_GetRandomPostID]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Post_GetRandomPostID]
GO


CREATE PROCEDURE dbo.cs_Post_GetRandomPostID
	@SettingsID int,
	@CategoryID int=-1,
	@SectionID int
AS
SET Transaction Isolation Level Read UNCOMMITTED

if @CategoryID = -1
begin
	select top 1 PostID
		from cs_Posts
		where PostID = ParentID
			and SettingsID = @SettingsID
			and SectionID = @SectionID
			order by newid()
end
else
begin
	select P.PostID
		from cs_Posts P
		join cs_Posts_InCategories C on C.PostID = P.PostID
		where P.PostID = P.ParentID
			and P.SettingsID = @SettingsID
			and P.SectionID = @SectionID
			and C.CategoryID = @CategoryID
			order by newid()
end
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_Post_GetRandomPostID] to public
go
/***********************************************
* Sproc: cs_Post_GetRating
* File Date: 11/29/2006 10:07:31 AM
***********************************************/
Print 'Creating...cs_Post_GetRating'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Post_GetRating]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Post_GetRating]
GO

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO


/***********************************************
* Sproc: cs_post_IsTracked
* File Date: 11/29/2006 10:07:31 AM
***********************************************/
Print 'Creating...cs_post_IsTracked'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_thread_IsTracked]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_thread_IsTracked]
GO

CREATE  PROCEDURE [dbo].cs_thread_IsTracked
(
	@SettingsID int,
	@ThreadID int,
	@UserID int,
	@IsTracked bit output
)
AS
SET Transaction Isolation Level Read UNCOMMITTED
BEGIN

IF EXISTS(SELECT ThreadID FROM cs_TrackedThreads (nolock) WHERE ThreadID = @ThreadID AND UserID=@UserID and SettingsID = @SettingsID)
	SELECT @IsTracked = 1
ELSE
	SELECT @IsTracked = 0

END



GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_thread_IsTracked] to public
go
/***********************************************
* Sproc: cs_Post_Rate
* File Date: 11/29/2006 10:07:34 AM
***********************************************/
Print 'Creating...cs_Post_Rate'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Post_Rate]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Post_Rate]
GO

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO


/***********************************************
* Sproc: cs_Post_ToggleSettings
* File Date: 11/29/2006 10:07:31 AM
***********************************************/
Print 'Creating...cs_Post_ToggleSettings'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Post_ToggleSettings]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Post_ToggleSettings]
GO

CREATE   procedure [dbo].cs_Post_ToggleSettings
(
	@PostID int,
	@IsAnnouncement bit,
	@IsLocked bit,
	@ModeratorID int,
	@SettingsID int
)
AS
SET Transaction Isolation Level Read UNCOMMITTED
BEGIN
	DECLARE @CurrentLockState bit
	DECLARE @CurrentAnnouncementState bit
	
	DECLARE @ThreadID int
	DECLARE @PostLevel int
	SELECT 
		@ThreadID = ThreadID, 
		@PostLevel = PostLevel 
	FROM 
		cs_Posts 
	WHERE 
		PostID = @PostID

-- Is this a thread
IF @PostLevel =1
BEGIN
	print 'Toggling settings on a thread.'

	-- Get the current state of the thread
	SELECT 
		@CurrentLockState = IsLocked
	FROM 
		cs_Threads 
	WHERE 
		ThreadID = @ThreadID

	-- Get current is announcement state of the thread
	IF EXISTS (	SELECT 
				ThreadID 
			FROM 
				cs_Threads
			WHERE
				ThreadID = @ThreadID 
				AND IsSticky = 1
				AND StickyDate > DateAdd( y, 20, GetDate() )
			)

		SET @CurrentAnnouncementState = 1
	ELSE
		SET @CurrentAnnouncementState = 0
		

	-- Is the Post getting locked?
	IF @CurrentLockState != @IsLocked
	BEGIN
		UPDATE
			cs_Threads
		SET
			IsLocked = @IsLocked
		WHERE
			ThreadID = @ThreadID

		UPDATE
			cs_Posts
		SET
			IsLocked = @IsLocked
		WHERE
			ThreadID = @ThreadID

		IF @IsLocked = 0
		BEGIN
		 	exec cs_system_ModerationAction_AuditEntry 6, @ModeratorID, @ThreadID, null, null, @SettingsID
			-- added as a result of testings
			--
		 	exec cs_system_ModerationAction_AuditEntry 6, @ModeratorID, @PostID, null, null, @SettingsID
		END
        		ELSE
		BEGIN
			exec cs_system_ModerationAction_AuditEntry 5, @ModeratorID, @ThreadID, null, null, @SettingsID
			-- added as a result of testings
			--
			exec cs_system_ModerationAction_AuditEntry 5, @ModeratorID, @PostID, null, null, @SettingsID
		END
	END


	-- Is the post an Annoucement
	IF @CurrentAnnouncementState != @IsAnnouncement
		IF @IsAnnouncement = 1
		BEGIN
			UPDATE
				cs_Threads
			SET
				IsSticky = 1,
				StickyDate = DateAdd(y, 25, ThreadDate)
			WHERE
				ThreadID = @ThreadID
	
			exec cs_system_ModerationAction_AuditEntry 16, @ModeratorID, @PostID, null, null, @SettingsID
	
		END
		ELSE
		BEGIN
			UPDATE
				cs_Threads
			SET
				IsSticky = 0,
				StickyDate = ThreadDate
			WHERE
				ThreadID = @ThreadID
	
			exec cs_system_ModerationAction_AuditEntry 17, @ModeratorID, @PostID, null, null, @SettingsID
		END
END
ELSE
	print 'Toggling settings on a post.'

	-- Get the current lock state of the thread
	SELECT 
		@CurrentLockState = IsLocked
	FROM 
		cs_Posts 
	WHERE 
		PostID = @PostID

	-- UPDATE The child posts
	UPDATE
	   	cs_Posts
	SET
		IsLocked = @IsLocked
	WHERE
		ParentID = @PostID
	
	IF @IsLocked != @CurrentLockState
		IF @IsLocked = 0
		  exec cs_system_ModerationAction_AuditEntry 6, @ModeratorID, @PostID, null, null, @SettingsID
	        ELSE
		  exec cs_system_ModerationAction_AuditEntry 5, @ModeratorID, @PostID, null, null, @SettingsID
END
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_Post_ToggleSettings] to public
go
/***********************************************
* Sproc: cs_Post_Update
* File Date: 11/29/2006 10:07:31 AM
***********************************************/
Print 'Creating...cs_Post_Update'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Post_Update]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Post_Update]
GO

CREATE PROCEDURE [dbo].cs_Post_Update
(
	@SectionID	int = null,
	@PostID	int,
	@Subject	nvarchar(256),
	@Body		ntext,
	@FormattedBody	ntext,
	@EmoticonID	int = 0,
	@IsSticky 	bit = null,
	@StickyDate 	datetime = null,
	@IsLocked	bit,
	@IsAnnouncement bit,
	@EditedBy	int,
	@EditNotes	ntext = null,
	@PropertyNames ntext = null,
	@PropertyValues ntext = null,
	@SettingsID int,
	@PostConfiguration int = 0,
	@PostName nvarchar(256) =  null,
	@IsApproved bit = null,
	@Points int = 0,
	@PostMedia int = null,
	@PostDate datetime = null,
	@PostStatus int = null,
	@SpamScore int = null
)
AS
	-- This sproc updates a post

	DECLARE @ThreadID int
	DECLARE @CurrentStickyDate datetime
	DECLARE @ParentID int
	--DECLARE @CurrentIsSticky BIT
	--DECLARE @CurrentSubject NVARCHAR(256)
	--DECLARE @StickyHasRemoved BIT
	--DECLARE @SubjectHasChanged BIT
	
	-- Get the thread and postdate this applies to
	SELECT 
		@ThreadID = P.ThreadID,
		@CurrentStickyDate = T.StickyDate,
		@ParentID = P.ParentID,
		@SectionID = P.SectionID
		--@CurrentIsSticky = T.IsSticky,
		--@CurrentSubject = P.Subject
	FROM 
		cs_Posts P
	LEFT JOIN
		cs_Threads T ON T.ThreadID = P.ThreadID
	WHERE 
		P.PostID = @PostID AND P.SettingsID = @SettingsID
	
	-- Check if subject has changed or stickiness has been removed.
	--SET @StickyHasRemoved = 0
	--SET @SubjectHasChanged = 0

	--IF (@IsSticky IS NOT NULL) AND (@IsSticky = 0) AND (@CurrentIsSticky = 1)
	--	SET @StickyHasRemoved = 1		
	
	--IF (@CurrentSubject <> @Subject)		
	--	SET @SubjectHasChanged = 1

	-- Update post's details
	UPDATE 
		cs_Posts 
	SET
		Subject = @Subject,
		Body = @Body,
		FormattedBody = @FormattedBody,
		IsLocked = @IsLocked,
		EmoticonID = @EmoticonID,
		PropertyNames = @PropertyNames,
		PropertyValues = @PropertyValues,
		PostConfiguration = @PostConfiguration,
		PostName = @PostName,
		Points = @Points,
		IsApproved = IsNull(@IsApproved, IsApproved),
		PostMedia = IsNull(@PostMedia, PostMedia),
		PostStatus = IsNull(@PostStatus, PostStatus),
		SpamScore = IsNull(@SpamScore, SpamScore)
	WHERE 
		PostID = @PostID AND SettingsID = @SettingsID

	if(@PostID = @ParentID AND @IsApproved is not null)
	Begin
		Update cs_Threads Set IsApproved = @IsApproved Where ThreadID = @ThreadID
	End
	
	/*
	-- We need not to trigger thread and section stats rebuild if sticky has been 
	-- removed or subject has been changed.
	-- If something else has changed then we will trigger stats rebuild of info 
	-- but not the dates (is the meaning of 0, a new param).

	-- Update most recent info in cs_Threads but not any date
	IF (@ThreadID > 0) AND (@StickyHasRemoved = 0) AND (@SubjectHasChanged = 0) 
		EXEC cs_system_UpdateThread @ThreadID, @PostID, @SettingsID, 0
	
	-- Update most recent info in cs_Sections but not any date
	IF (@SectionID > 0) AND (@StickyHasRemoved = 0) AND (@SubjectHasChanged = 0)
		EXEC cs_system_UpdateForum @SectionID, @ThreadID, @PostID, @SettingsID, 0
	*/

	IF (@PostStatus IS NOT NULL)
		EXEC cs_Thread_Status_Update @ThreadID, null, @SettingsID

	-- Allow thread to update sticky properties.
	-- Also if this post got locked, then mark the thread locked too
	IF (@IsSticky IS NOT NULL) AND (@StickyDate IS NOT NULL)
	BEGIN
		DECLARE @ThreadIsLocked BIT
		SET @ThreadIsLocked = (@IsAnnouncement | @IsLocked)
	 
		IF (@StickyDate > '1/1/2000')
		BEGIN
			-- valid date range given
			UPDATE
				cs_Threads
			SET
				IsSticky = @IsSticky,
				StickyDate = @StickyDate,
				IsLocked = @ThreadIsLocked
			WHERE 
				ThreadID = @ThreadID  AND SettingsID = @SettingsID
		END
		ELSE BEGIN
			-- trying to remove a sticky
			UPDATE
				cs_Threads
			SET
				IsSticky = @IsSticky,
				StickyDate = @CurrentStickyDate,
				IsLocked = @ThreadIsLocked
			WHERE 
				ThreadID = @ThreadID AND SettingsID = @SettingsID 		
		END
	END

	IF @EditNotes IS NOT NULL
	BEGIN
		IF EXISTS (SELECT PostID FROM cs_PostEditNotes WHERE PostID = @PostID)
			UPDATE 
				cs_PostEditNotes
			SET
				EditNotes = @EditNotes
			WHERE	
				PostID = @PostID AND SettingsID = @SettingsID
		ELSE
			INSERT INTO
				cs_PostEditNotes
			VALUES
				(@PostID, @EditNotes, @SettingsID)
	END
	
	IF @PostDate IS NOT NULL
	BEGIN
			UPDATE cs_Posts	SET	PostDate = @PostDate WHERE PostID = @PostID AND SettingsID = @SettingsID
			
			if(@PostID = @ParentID)
			Begin
				Update cs_Threads Set PostDate = @PostDate Where ThreadID = @ThreadID AND SettingsID = @SettingsID
			End
	END

	-- update thread emoticon if this is a thread starter
	IF (@PostID = @ParentID)
	BEGIN
		UPDATE cs_Threads SET ThreadEmoticonID = @EmoticonID WHERE ThreadID = @ThreadID AND SettingsID = @SettingsID
	END
	
	-- Mark thread as not read for anyone but the editor
	DELETE cs_ThreadsRead WHERE ThreadID = @ThreadID AND SettingsID = @SettingsID AND UserID <> @EditedBy 

	-- We want to track what happened
	exec cs_system_ModerationAction_AuditEntry 2, @EditedBy, @PostID, NULL, NULL, @SettingsID, @EditNotes

	EXEC cs_system_ResetThreadStatistics @ThreadID
	IF @SectionID > 0	-- passing in "0" will recalculate stats for ALL sections (timeout on large sites)
	BEGIN
		EXEC cs_system_ResetForumStatistics @SectionID
	END
	EXEC cs_Posts_UpdatePostsInCategories @SectionID = @SectionID, @PostID = null
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT  EXECUTE  ON [dbo].[cs_Post_Update]  TO [public]
GO


/***********************************************
* Sproc: cs_PrivateMessages_CreateDelete
* File Date: 11/29/2006 10:07:31 AM
***********************************************/
Print 'Creating...cs_PrivateMessages_CreateDelete'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO


if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_PrivateMessages_CreateDelete]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_PrivateMessages_CreateDelete]
GO

CREATE  procedure [dbo].cs_PrivateMessages_CreateDelete
(
	@UserID int,
	@ThreadID int,
	@SettingsID int,
	@Action int
)
AS
SET Transaction Isolation Level Read UNCOMMITTED
BEGIN

IF (@Action = 0)
BEGIN
	-- Does the user already have the ability to see this thread?
	IF EXISTS (SELECT UserID FROM cs_PrivateMessages WHERE UserID = @UserID and ThreadID = @ThreadID and SettingsID = @SettingsID)
		RETURN
	
	INSERT INTO
		cs_PrivateMessages
	VALUES
	(
		@UserID,
		@ThreadID,
		@SettingsID
	)
	
	RETURN
END
	
IF (@Action = 2)
BEGIN
	-- This is a thread level delete operation ... and it works like this:
	-- as long as one of the pairs has the message in its list we don't want to delete 
	-- thread related data but only its link to that message. 
	
	-- The SectionID for any PM thread is 0
	DECLARE @SectionID INT
	SET @SectionID = 0
	 
	-- Delete user's link to this PM thread
	DELETE
		cs_PrivateMessages
	WHERE
		UserID = @UserID AND
		ThreadID = @ThreadID AND 
		SettingsID = @SettingsID
	
	-- Find out if there are any other pair that are bound to this PM thread.
	-- If no one is found then we may delete thread related data
	IF NOT EXISTS( SELECT UserID FROM cs_PrivateMessages WHERE ThreadID = @ThreadID AND SettingsID = @SettingsID )
	BEGIN
		-- Delete thread related data
		EXEC cs_Thread_Delete @SettingsID, @SectionID, @ThreadID, 0, @UserID, ''
	END
END
	
END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO


grant execute on [dbo].[cs_PrivateMessages_CreateDelete] to public
go
/***********************************************
* Sproc: cs_PrivateMessages_Recipients
* File Date: 11/29/2006 10:07:31 AM
***********************************************/
Print 'Creating...cs_PrivateMessages_Recipients'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_PrivateMessages_Recipients]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_PrivateMessages_Recipients]
GO


CREATE procedure [dbo].cs_PrivateMessages_Recipients (
	@ThreadID as int,
	@SettingsID as int
)
AS
SET Transaction Isolation Level Read UNCOMMITTED

BEGIN
	SELECT 
		PM.UserID,
		U.UserName
	FROM 
		cs_vw_Users_FullUser U,
		cs_PrivateMessages PM
	WHERE 
		PM.ThreadID = @ThreadID AND
		PM.SettingsID = @SettingsID AND
		PM.UserID = U.cs_UserID
END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_PrivateMessages_Recipients] to public
go
/***********************************************
* Sproc: cs_PrivateMessages_UnreadCount
* File Date: 11/29/2006 10:07:29 AM
***********************************************/
Print 'Creating...cs_PrivateMessages_UnreadCount'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_PrivateMessages_UnreadCount]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_PrivateMessages_UnreadCount]
GO


create procedure [dbo].[cs_PrivateMessages_UnreadCount] (
	@SettingsID	int,
	@UserID		int
)
AS
BEGIN
	-- Ensure data integrity
	DELETE
		cs_PrivateMessages
	WHERE
		ThreadID not in (SELECT ThreadID from cs_Threads)

	SELECT ThreadID  FROM cs_PrivateMessages WHERE  SettingsID = @SettingsID AND UserID = @UserID
	exec dbo.cs_forums_threads_ThreadsRead 0, @UserID, @SettingsID

END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT EXECUTE on [dbo].[cs_PrivateMessages_UnreadCount]  to public
GO
/***********************************************
* Sproc: cs_Ranks_Get
* File Date: 11/29/2006 10:07:31 AM
***********************************************/
Print 'Creating...cs_Ranks_Get'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Ranks_Get]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Ranks_Get]
GO







create proc [dbo].cs_Ranks_Get
(
	@SettingsID int
)
AS
SET Transaction Isolation Level Read UNCOMMITTED
	SELECT r.*
	FROM
		cs_Ranks r where SettingsID = @SettingsID







GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_Ranks_Get] to public
go
/***********************************************
* Sproc: cs_Rank_CreateUpdateDelete
* File Date: 11/29/2006 10:07:31 AM
***********************************************/
Print 'Creating...cs_Rank_CreateUpdateDelete'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Rank_CreateUpdateDelete]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Rank_CreateUpdateDelete]
GO


CREATE proc [dbo].cs_Rank_CreateUpdateDelete
(
	@RankID				int out,
	@DeleteRank			bit	= 0,
	@RankName			nvarchar(60),
	@PostingCountMin	int,
	@PostingCountMax	int,	
	@RankIconUrl		nvarchar(512),
	@SettingsID int
)
AS
SET Transaction Isolation Level Read UNCOMMITTED
-- are we deleting the rank
IF( @DeleteRank = 1 )
BEGIN

	DELETE cs_Ranks
	WHERE
		RankID	= @RankID and SettingsID = @SettingsID

	RETURN
END

-- are we updating the rank
IF( @RankID >  0 )
BEGIN

	UPDATE cs_Ranks SET
		  RankName			= @RankName
		, PostingCountMin	= @PostingCountMin
		, PostingCountMax	= @PostingCountMax
		, RankIconUrl		= @RankIconUrl
	WHERE
		  RankID	= @RankID and SettingsID = @SettingsID
		

END
ELSE
BEGIN
	INSERT INTO cs_Ranks (
		RankName, PostingCountMin, PostingCountMax, RankIconUrl, SettingsID
	)
	VALUES( 
		@RankName, @PostingCountMin, @PostingCountMax, @RankIconUrl, @SettingsID
	)

	SET @RankID = @@identity
END

RETURN



GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_Rank_CreateUpdateDelete] to public
go
/***********************************************
* Sproc: cs_Ratings_Get
* File Date: 11/29/2006 10:07:35 AM
***********************************************/
Print 'Creating...cs_Ratings_Get'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Ratings_Get]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Ratings_Get]
GO

CREATE procedure dbo.cs_Ratings_Get
(
	@RatingType	int,
	@ItemID		int,
	@SettingsID	int
)
AS
	SET Transaction Isolation Level Read UNCOMMITTED

	IF @RatingType = 0			-- Post

		SELECT
			U.*,
			'Post' AS RatingType,
			R.PostID AS ItemID,
			R.Rating
		FROM
			cs_vw_Users_FullUser U,
			cs_PostRating R
		WHERE
			R.UserID = U.cs_UserID AND
			R.PostID = @ItemID AND U.SettingsID = @SettingsID and R.SettingsID = @SettingsID

	ELSE IF @RatingType = 1		-- Thread

		SELECT
			U.*,
			'Thread' AS RatingType,
			R.ThreadID AS ItemID,
			R.Rating
		FROM
			cs_vw_Users_FullUser U,
			cs_ThreadRating R
		WHERE
			R.UserID = U.cs_UserID AND
			R.ThreadID = @ItemID AND U.SettingsID = @SettingsID and R.SettingsID = @SettingsID


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT EXECUTE  ON [dbo].[cs_Ratings_Get] TO [public]
GO

/***********************************************
* Sproc: cs_Rating_Add
* File Date: 11/29/2006 10:07:30 AM
***********************************************/
Print 'Creating...cs_Rating_Add'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Rating_Add]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Rating_Add]
GO

CREATE PROCEDURE dbo.cs_Rating_Add
(
	@RatingType		int,
	@ItemID			int,
	@UserID			int,
	@Rating			int,
	@SettingsID		int
)
AS
	SET Transaction Isolation Level Read UNCOMMITTED

	IF @RatingType	= 0			-- Post
	BEGIN

		-- Add the rating
		INSERT INTO
			cs_PostRating
			(UserID, PostID, Rating, SettingsID)
		VALUES
			(@UserID, @ItemID, @Rating, @SettingsID)

		-- Update the post's rating stats
		UPDATE
			cs_Posts
		SET
			RatingSum = RatingSum + @Rating,
			TotalRatings = TotalRatings + 1
		WHERE
			PostID = @ItemID and SettingsID = @SettingsID
	END

	ELSE IF @RatingType = 1		-- Thread
	BEGIN

		-- Add the rating
		INSERT INTO
			cs_ThreadRating
			(UserID, ThreadID, Rating, SettingsID)
		VALUES
			(@UserID, @ItemID, @Rating, @SettingsID)

		-- Update the thread's rating stats
		UPDATE
			cs_Threads
		SET
			RatingSum = RatingSum + @Rating,
			TotalRatings = TotalRatings + 1
		WHERE
			ThreadID = @ItemID and SettingsID = @SettingsID
	END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT EXECUTE  ON [dbo].[cs_Rating_Add] TO [public]
GO

/***********************************************
* Sproc: cs_Rating_Get
* File Date: 11/29/2006 10:07:31 AM
***********************************************/
Print 'Creating...cs_Rating_Get'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Rating_Get]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Rating_Get]
GO

CREATE PROCEDURE dbo.cs_Rating_Get
(
	@RatingType	int,
	@ItemID		int,
	@UserID		int,
	@SettingsID	int,
	@Rating		int	OUTPUT
)
AS
	SET NOCOUNT ON
	SET Transaction Isolation Level Read UNCOMMITTED

	-- Setup default value (signifies not rated)
	SET	@Rating	= -1

	IF @RatingType = 0			--Post

		SELECT	@Rating = Rating
		FROM	cs_PostRating
		WHERE	UserID = @UserID
		AND		PostID = @ItemID
		AND		SettingsID = @SettingsID

	ELSE IF @RatingType = 1		--Thread

		SELECT	@Rating = Rating
		FROM	cs_ThreadRating
		WHERE	UserID = @UserID
		AND		ThreadID = @ItemID
		AND		SettingsID = @SettingsID

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT EXECUTE  ON [dbo].[cs_Rating_Get] TO [public]
GO

/***********************************************
* Sproc: cs_Rating_Rate
* File Date: 11/29/2006 10:07:34 AM
***********************************************/
Print 'Creating...cs_Rating_Rate'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Rating_Rate]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Rating_Rate]
GO

CREATE procedure dbo.cs_Rating_Rate
(
	@RatingType	int,
	@ItemID		int,
	@UserID		int,
	@Rating		int,
	@SettingsID	int
)
AS
	SET Transaction Isolation Level Read UNCOMMITTED

	-- Get existing rating
	DECLARE @CurrentRating	int
	EXECUTE cs_Rating_Get @RatingType, @ItemID, @UserID, @SettingsID, @CurrentRating OUTPUT
	
	-- Rating hasn't changed
	IF @Rating = @CurrentRating
		RETURN

	-- User has previously rated this item
	IF @CurrentRating >= 0

		-- Update the rating
		EXECUTE cs_Rating_Update @RatingType, @ItemID, @UserID, @Rating, @SettingsID, @CurrentRating

	ELSE

		-- Add the rating
		EXECUTE cs_Rating_Add @RatingType, @ItemID, @UserID, @Rating, @SettingsID

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT EXECUTE  ON [dbo].[cs_Rating_Rate] TO [public]
GO

/***********************************************
* Sproc: cs_Rating_Update
* File Date: 11/29/2006 10:07:30 AM
***********************************************/
Print 'Creating...cs_Rating_Update'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Rating_Update]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Rating_Update]
GO

CREATE PROCEDURE dbo.cs_Rating_Update
(
	@RatingType		int,
	@ItemID			int,
	@UserID			int,
	@Rating			int,
	@SettingsID		int,
	@CurrentRating	int
)
AS
	SET Transaction Isolation Level Read UNCOMMITTED

	IF @RatingType	= 0			-- Post
	BEGIN

		-- Update the rating
		UPDATE
			cs_PostRating
		SET 
			Rating = @Rating
		WHERE
			UserID = @UserID AND
			PostID = @ItemID and SettingsID = @SettingsID

		-- Update the post's rating stats
		UPDATE
			cs_Posts
		SET
			RatingSum = (RatingSum - @CurrentRating) + @Rating
		WHERE
			PostID = @ItemID and SettingsID = @SettingsID
	END

	ELSE IF @RatingType = 1		-- Thread
	BEGIN

		-- Update the rating
		UPDATE
			cs_ThreadRating
		SET 
			Rating = @Rating
		WHERE
			UserID = @UserID AND
			ThreadID = @ItemID and SettingsID = @SettingsID

		-- Update the thread's rating stats
		UPDATE
			cs_Threads
		SET
			RatingSum = (RatingSum - @CurrentRating) + @Rating
		WHERE
			ThreadID = @ItemID and SettingsID = @SettingsID
	END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT EXECUTE  ON [dbo].[cs_Rating_Update] TO [public]
GO

/***********************************************
* Sproc: cs_Referrals_Add
* File Date: 11/29/2006 10:07:30 AM
***********************************************/
Print 'Creating...cs_Referrals_Add'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_referrals_Add]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_referrals_Add]
GO

CREATE Proc [dbo].cs_referrals_Add
(
	@UrlID int,
	@Url nvarchar(512),
	@SettingsID int,
	@SectionID int,
	@PostID int	
)

as
SET Transaction Isolation Level Read UNCOMMITTED

exec cs_Urls_Add @UrlID, @Url

Declare @ReferralID int

Select @ReferralID = ReferralID FROM cs_Referrals where SettingsID = @SettingsID and SectionID = @SectionID and UrlID = @UrlID

if(@ReferralID is null)
Begin
	Insert cs_Referrals (SettingsID, SectionID, PostID, UrlID, Hits, LastDate)
	Values (@SettingsID, @SectionID, @PostID, @UrlID, 1, getdate())
End
Else
Begin
	Update cs_Referrals
	Set 
		Hits = Hits + 1,
		LastDate = getdate()
	Where ReferralID = @ReferralID
End



GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_referrals_Add] to public
go
/***********************************************
* Sproc: cs_referrals_Get
* File Date: 11/29/2006 10:07:33 AM
***********************************************/
Print 'Creating...cs_referrals_Get'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_referrals_Get]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_referrals_Get]
GO

CREATE Proc [dbo].cs_referrals_Get
(
	@SettingsID int,
	@SectionID int,
	@PostID int,
	@PageSize int,
	@PageIndex int,
	@TotalRecords int output
)
AS
SET Transaction Isolation Level Read UNCOMMITTED


-- are we getting referrals for a single post
IF (@PostID <> -1)
BEGIN

	-- return all referrals (no paging)
	SELECT
		P.Subject,
		R.ReferralID,
		R.SettingsID,
		R.SectionID,
		P.PostID,
		U.Url,
		R.Hits,
		R.LastDate
	FROM
		cs_Referrals R
		INNER JOIN cs_Urls U ON R.UrlID = U.UrlID
		INNER JOIN cs_Posts P ON R.PostID = P.PostID
	WHERE
		R.SettingsID = @SettingsID
		AND R.SectionID = @SectionID
		AND R.PostID = @PostID
	ORDER BY
		R.LastDate DESC	

	-- return record count
	SELECT
		@TotalRecords = COUNT(*)
	FROM
		cs_Referrals R
	WHERE
		R.SettingsID = @SettingsID
		AND R.SectionID = @SectionID
		AND R.PostID = @PostID

	-- exit immediately
	RETURN
END


-- we are getting referrals for multiple posts (use paging)
DECLARE @RowsToReturn int
DECLARE @PageLowerBound int
DECLARE @PageUpperBound int

SET @RowsToReturn = @PageSize * (@PageIndex + 1)
SET ROWCOUNT @RowsToReturn
SET @PageLowerBound = @PageSize * @PageIndex
SET @PageUpperBound = @PageLowerBound + @PageSize + 1

CREATE TABLE #PageIndex 
(
	IndexID int IDENTITY (1, 1) NOT NULL,
	ReferralID int
)

Insert #PageIndex (ReferralID)
Select ReferralID FROM cs_Referrals where SettingsID = @SettingsID and  SectionID = @SectionID order by LastDate desc

-- Reset rowcount and get count of total records
SET ROWCOUNT 0
Select @TotalRecords = count(*) From cs_Referrals Where SettingsID = @SettingsID and SectionID = @SectionID

Select  cs_Posts.Subject,  cs_Referrals.ReferralID, cs_Referrals.SettingsID,  cs_Referrals.SectionID, cs_Posts.PostID, Url, Hits, LastDate
FROM cs_Referrals, cs_Urls, #PageIndex, cs_Posts
Where
	cs_Referrals.ReferralID = #PageIndex.ReferralID and
	cs_Urls.UrlID = cs_Referrals.UrlID and 
	#PageIndex.IndexID > @PageLowerBound AND
	#PageIndex.IndexID < @PageUpperBound AND 
	cs_Posts.PostID = cs_Referrals.PostID
Order by IndexID

DROP Table #PageIndex


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_referrals_Get] to public
go
/***********************************************
* Sproc: cs_RemoveAllPostTracking
* File Date: 11/29/2006 10:07:31 AM
***********************************************/
Print 'Creating...cs_RemoveAllPostTracking'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_RemoveAllPostTracking]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_RemoveAllPostTracking]
GO



CREATE PROCEDURE [dbo].cs_RemoveAllPostTracking
(
	@UserID int = NULL,
	@SectionID int = NULL,
	@SettingsID int
)
AS
SET Transaction Isolation Level Read UNCOMMITTED

IF (@UserID IS NOT NULL)
	IF (@SectionID IS NOT NULL)
		DELETE cs_TrackedThreads 
		FROM 
			cs_TrackedThreads tt INNER JOIN cs_Threads AS t
			ON tt.ThreadID = t.ThreadID
		WHERE 
			t.SectionID = @SectionID AND 
			tt.UserID = @UserID AND 
			tt.SettingsID = @SettingsID
				
	ELSE
		DELETE FROM cs_TrackedThreads WHERE UserID = @UserID AND SettingsID = @SettingsID	
ELSE
	IF (@SectionID IS NOT NULL)
		DELETE cs_TrackedThreads 
		FROM 
			cs_TrackedThreads tt INNER JOIN cs_Threads AS t
			ON tt.ThreadID = t.ThreadID
		WHERE 
			t.SectionID = @SectionID AND 
			tt.SettingsID = @SettingsID

	ELSE
		DELETE FROM cs_TrackedThreads WHERE SettingsID = @SettingsID	

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_RemoveAllPostTracking] to public
go
/***********************************************
* Sproc: cs_RemoveAllSectionTracking
* File Date: 11/29/2006 10:07:32 AM
***********************************************/
Print 'Creating...cs_RemoveAllSectionTracking'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_RemoveAllSectionTracking]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_RemoveAllSectionTracking]
GO


CREATE PROCEDURE [dbo].cs_RemoveAllSectionTracking
(
	@UserID int = NULL,
	@SectionID int = NULL,
	@SettingsID int
)
AS
SET Transaction Isolation Level Read UNCOMMITTED

IF (@UserID IS NOT NULL)
	IF (@SectionID IS NOT NULL)			
		DELETE FROM cs_TrackedSections WHERE UserID = @UserID AND SectionID = @SectionID AND SettingsID = @SettingsID			
	ELSE
		DELETE FROM cs_TrackedSections WHERE UserID = @UserID AND SettingsID = @SettingsID			
ELSE
	IF (@SectionID IS NOT NULL)
		DELETE FROM cs_TrackedSections WHERE SectionID = @SectionID AND SettingsID = @SettingsID			
	ELSE
		DELETE FROM cs_TrackedSections WHERE SettingsID = @SettingsID
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_RemoveAllSectionTracking] to public
go
/***********************************************
* Sproc: cs_Reports_Get
* File Date: 11/29/2006 10:07:30 AM
***********************************************/
Print 'Creating...cs_Reports_Get'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Reports_Get]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Reports_Get]
GO







create proc [dbo].cs_Reports_Get
(
	@ReportID	int = 0,
	@SettingsID int
)
as
SET Transaction Isolation Level Read UNCOMMITTED
	select
		*
	FROM
		cs_Reports
	WHERE
		ReportID = @ReportID or
		( 
			@ReportID = 0 AND
			1=1
		) and SettingsID = @SettingsID






GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_Reports_Get] to public
go
/***********************************************
* Sproc: cs_Report_CreateUpdateDelete
* File Date: 11/29/2006 10:07:33 AM
***********************************************/
Print 'Creating...cs_Report_CreateUpdateDelete'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Report_CreateUpdateDelete]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Report_CreateUpdateDelete]
GO

create proc [dbo].cs_Report_CreateUpdateDelete
(
	  @ReportID			int out
	, @DeleteReport		bit		= 0
	, @ReportName		varchar(20)
	, @Active			bit
	, @ReportCommand	varchar(6500)
	, @ReportScript		ntext
	, @SettingsID 		int
)
AS

IF( @DeleteReport > 0 )
BEGIN
	DELETE cs_Reports
	WHERE
		ReportID	= @ReportID and SettingsID = @SettingsID
	RETURN
END

IF( @ReportID > 0 )
BEGIN
	UPDATE cs_Reports SET
		  ReportName	= @ReportName
		, Active		= @Active
		, ReportCommand	= @ReportCommand
		, ReportScript	= @ReportScript
	WHERE
		ReportID	= @ReportID and SettingsID = @SettingsID
END
ELSE
BEGIN	
	INSERT INTO cs_Reports ( 
		ReportName, Active, ReportCommand, ReportScript, SettingsID 
	) VALUES (
		@ReportName, @Active, @ReportCommand, @ReportScript, @SettingsID
	)	

	SET @ReportID = @@identity
END
RETURN







GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_Report_CreateUpdateDelete] to public
go
/***********************************************
* Sproc: cs_report_GetBlogPostReplies
* File Date: 11/29/2006 10:07:31 AM
***********************************************/
Print 'Creating...cs_report_GetBlogPostReplies'

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_report_GetBlogPostReplies]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_report_GetBlogPostReplies]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO



CREATE  PROCEDURE [dbo].cs_report_GetBlogPostReplies
(
        @BegReportDate DATETIME
	,@EndReportDate DATETIME
)

AS
BEGIN

-- declare @BegReportDate DateTime
-- set @BegReportDate = '3/6/2006'
-- declare @EndReportDate DateTime
-- set @EndReportDate = '3/7/2006'

-- Most Replies To Forum Posts --
SELECT
	p.PostID, t.Replies, p.Subject
FROM
(
	SELECT TOP 25
		  posts.ThreadID
		,(Select COUNT(p2.ThreadID) from cs_Posts p2 where p2.ThreadID = posts.ThreadID AND p2.PostID != p2.ParentID AND p2.PostDate between @BegReportDate and @EndReportDate) AS Replies
	FROM
		cs_Sections sections
		INNER JOIN cs_Threads threads ON sections.SectionID = threads.SectionID
	        INNER JOIN cs_Posts posts ON threads.ThreadID = posts.ThreadID
	WHERE
		posts.PostDate between @BegReportDate and @EndReportDate
	        AND sections.ApplicationType = 1
	GROUP BY
		posts.ThreadID
	ORDER BY
		Replies DESC
) AS t
INNER JOIN
	cs_Posts p on t.ThreadID = p.ThreadID
WHERE
	p.PostID = p.ParentID
END



GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_report_GetBlogPostReplies] to public
go

/***********************************************
* Sproc: cs_report_GetBlogPostViews
* File Date: 11/29/2006 10:07:31 AM
***********************************************/
Print 'Creating...cs_report_GetBlogPostViews'

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_report_GetBlogPostViews]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_report_GetBlogPostViews]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO



CREATE  PROCEDURE [dbo].cs_report_GetBlogPostViews
(
        @BegReportDate DATETIME
	,@EndReportDate DATETIME
)

AS
BEGIN

-- declare @BegReportDate DateTime
-- set @BegReportDate = '3/6/2006'
-- declare @EndReportDate DateTime
-- set @EndReportDate = '3/7/2006'

-- Most Viewed Blog Posts --
SELECT
	p.PostID, t.TViews, p.Subject
FROM
(
	SELECT TOP 25
		  posts.ThreadID
		,(Select SUM(p2.TotalViews) from cs_Posts p2 where p2.ThreadID = posts.ThreadID AND p2.PostDate between @BegReportDate and @EndReportDate) AS TViews
	FROM
		cs_Sections sections
		INNER JOIN cs_Threads threads ON sections.SectionID = threads.SectionID
	        INNER JOIN cs_Posts posts ON threads.ThreadID = posts.ThreadID
	WHERE
		posts.PostDate between @BegReportDate and @EndReportDate
	        AND sections.ApplicationType = 1
	GROUP BY
		posts.ThreadID
	ORDER BY
		TViews DESC
) AS t
INNER JOIN
	cs_Posts p on t.ThreadID = p.ThreadID
WHERE
	p.PostID = p.ParentID
END


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_report_GetBlogPostViews] to public
go

/***********************************************
* Sproc: cs_report_GetForumPostReplies
* File Date: 11/29/2006 10:07:31 AM
***********************************************/
Print 'Creating...cs_report_GetForumPostReplies'

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_report_GetForumPostReplies]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_report_GetForumPostReplies]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO


CREATE PROCEDURE [dbo].cs_report_GetForumPostReplies
(
        @BegReportDate DATETIME
	,@EndReportDate DATETIME
)

AS
BEGIN

-- declare @BegReportDate DateTime
-- set @BegReportDate = '3/6/2006'
-- declare @EndReportDate DateTime
-- set @EndReportDate = '3/7/2006'

-- Most Replies To Forum Posts --
SELECT
	p.PostID, t.Replies, p.Subject
FROM
(
	SELECT TOP 25
		  posts.ThreadID
		,(Select COUNT(p2.ThreadID) from cs_Posts p2 where p2.ThreadID = posts.ThreadID AND p2.PostID != p2.ParentID AND p2.PostDate between @BegReportDate and @EndReportDate) AS Replies
	FROM
		cs_Sections sections
		INNER JOIN cs_Threads threads ON sections.SectionID = threads.SectionID
	        INNER JOIN cs_Posts posts ON threads.ThreadID = posts.ThreadID
	WHERE
		posts.PostDate between @BegReportDate and @EndReportDate
	        AND sections.ApplicationType = 0
	GROUP BY
		posts.ThreadID
	ORDER BY
		Replies DESC
) AS t
INNER JOIN
	cs_Posts p on t.ThreadID = p.ThreadID
WHERE
	p.PostID = p.ParentID
END


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_report_GetForumPostReplies] to public
go

/***********************************************
* Sproc: cs_report_GetForumPostViews
* File Date: 11/29/2006 10:07:33 AM
***********************************************/
Print 'Creating...cs_report_GetForumPostViews'

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_report_GetForumPostViews]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_report_GetForumPostViews]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO


CREATE PROCEDURE [dbo].cs_report_GetForumPostViews
(
        @BegReportDate DATETIME
	,@EndReportDate DATETIME
)

AS
BEGIN

-- declare @BegReportDate DateTime
-- set @BegReportDate = '3/6/2006'
-- declare @EndReportDate DateTime
-- set @EndReportDate = '3/7/2006'

-- Most Viewed Forum Posts --
SELECT
	p.PostID, t.TViews, p.Subject
FROM
(
	SELECT TOP 25
		  posts.ThreadID
		,(Select SUM(p2.TotalViews) from cs_Posts p2 where p2.ThreadID = posts.ThreadID AND p2.PostDate between @BegReportDate and @EndReportDate) AS TViews
	FROM
		cs_Sections sections
		INNER JOIN cs_Threads threads ON sections.SectionID = threads.SectionID
	        INNER JOIN cs_Posts posts ON threads.ThreadID = posts.ThreadID
	WHERE
		posts.PostDate between @BegReportDate and @EndReportDate
	        AND sections.ApplicationType = 0
	GROUP BY
		posts.ThreadID
	ORDER BY
		TViews DESC
) AS t
INNER JOIN
	cs_Posts p on t.ThreadID = p.ThreadID
WHERE
	p.PostID = p.ParentID
END


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_report_GetForumPostViews] to public
go

/***********************************************
* Sproc: cs_ReverseTrackingOption
* File Date: 11/29/2006 10:07:31 AM
***********************************************/
Print 'Creating...cs_ReverseTrackingOption'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_ReverseTrackingOption]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_ReverseTrackingOption]
GO


create procedure [dbo].cs_ReverseTrackingOption 
(
	@UserID int,
	@ThreadID	int,
	@SettingsID int
)
AS
SET Transaction Isolation Level Read UNCOMMITTED
	-- reverse the user's tracking options for a particular thread
	-- first get the threadID of the Post

	IF EXISTS(SELECT ThreadID FROM cs_TrackedThreads WHERE ThreadID = @ThreadID AND UserID = @UserID and SettingsID = @SettingsID)
		-- the user is tracking this thread, delete this row
		DELETE FROM cs_TrackedThreads
		WHERE ThreadID = @ThreadID AND UserID = @UserID and SettingsID = @SettingsID
	ELSE
		-- this user isn't tracking the thread, so add her
		INSERT INTO cs_TrackedThreads (ThreadID, UserID, DateCreated, SettingsID)
		VALUES(@ThreadID, @UserID, GetDate(), @SettingsID)







GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_ReverseTrackingOption] to public
go
/***********************************************
* Sproc: cs_RoleQuotas_Get
* File Date: 11/29/2006 10:07:32 AM
***********************************************/
Print 'Creating...cs_RoleQuotas_Get'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_RoleQuotas_Get]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_RoleQuotas_Get]
GO

CREATE PROCEDURE dbo.cs_RoleQuotas_Get
(
	@SettingsID int
)

AS
	/* SET NOCOUNT ON */
	SELECT RoleID, DiskQuota, ImageQuota
	FROM cs_RoleQuotas
	WHERE SettingsID = @SettingsID
	RETURN 

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_RoleQuotas_Get] to public
go

/***********************************************
* Sproc: cs_RoleQuota_CreateUpdateDelete
* File Date: 11/29/2006 10:07:31 AM
***********************************************/
Print 'Creating...cs_RoleQuota_CreateUpdateDelete'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_RoleQuota_CreateUpdateDelete]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_RoleQuota_CreateUpdateDelete]
GO

CREATE PROCEDURE dbo.cs_RoleQuota_CreateUpdateDelete
(
	@RoleID uniqueidentifier,
	@DiskQuota bigint = -1,
	@ImageQuota int = -1,
	@SettingsID int
)

AS
	IF @DiskQuota = -1 AND @ImageQuota = -1
		DELETE FROM cs_RoleQuotas WHERE RoleID = @RoleID AND SettingsID = @SettingsID
	ELSE
	BEGIN
		DECLARE @Exists bit
	
		SELECT @Exists = COUNT(*) FROM cs_RoleQuotas WHERE RoleID = @RoleID AND SettingsID = @SettingsID
		IF @Exists = 0
			INSERT INTO cs_RoleQuotas (RoleID, DiskQuota, ImageQuota, SettingsID) VALUES (@RoleID, @DiskQuota, @ImageQuota, @SettingsID)
		ELSE
			UPDATE cs_RoleQuotas SET DiskQuota = @DiskQuota, ImageQuota = @ImageQuota WHERE RoleID = @RoleID AND SettingsID = @SettingsID
	END
	RETURN 

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_RoleQuota_CreateUpdateDelete] to public
go

/***********************************************
* Sproc: cs_Roles_CreateUpdateDelete
* File Date: 11/29/2006 10:07:31 AM
***********************************************/
Print 'Creating...cs_Roles_CreateUpdateDelete'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Roles_CreateUpdateDelete]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Roles_CreateUpdateDelete]
GO







-- sp_helptext cs_Roles_CreateUpdateDelete


CREATE PROCEDURE [dbo].cs_Roles_CreateUpdateDelete
(
	@RoleID	uniqueidentifier out,
	@DeleteRole	bit = 0,
	@Name		nvarchar(256) = '',
	@Description	nvarchar(512) = '',
	@SettingsID int

)
AS
DECLARE	@ApplicationName nvarchar(256)
Select @ApplicationName = ApplicationName from cs_SiteSettings where SettingsID = @SettingsID

DECLARE @ApplicationId UNIQUEIDENTIFIER
SELECT  @ApplicationId = NULL
SELECT  @ApplicationId = ApplicationId FROM aspnet_Applications WHERE LOWER(@ApplicationName) = LoweredApplicationName

if(@ApplicationId IS NULL)
RETURN
 

IF @RoleID is not null
Begin

	--validate application/role context
	IF NOT EXISTS(Select RoleId FROM aspnet_Roles where RoleId = @RoleID  and ApplicationId = @ApplicationId)
	RETURN


	-- Are we deleting the role?
	IF @DeleteRole = 1
	BEGIN
	
		-- delete all users in the role
		DELETE 
			aspnet_UsersInRoles
		WHERE 
			RoleId = @RoleID

		-- delete all product permissions using the role
		DELETE 
			cs_ProductPermissions
		WHERE 
			RoleID = @RoleID and SettingsID = @SettingsID
	
		-- delete all section permissions using the role
		DELETE 
			cs_SectionPermissions
		WHERE 
			RoleID = @RoleID and SettingsID = @SettingsID
	
	
		-- finally we can delete the actual role
		DELETE 
			aspnet_Roles
		WHERE 
			RoleId = @RoleID
	
	END
	ELSE
	BEGIN -- Are we updating a forum
		-- Update the role
		UPDATE 
			aspnet_Roles
		SET
			RoleName = @Name,
			LoweredRoleName = Lower(@Name),
			Description = @Description
		WHERE 
			RoleId = @RoleID
	END
END
ELSE
BEGIN

	-- Create a new Forum
	INSERT INTO 
		aspnet_Roles (
			RoleName, 
			LoweredRoleName,
			Description
			)
		VALUES (
			@Name,
			Lower(@Name),
			@Description
			)
	
	Select @RoleID = RoleId FROM aspnet_Roles where LoweredRoleName = Lower(@Name) and ApplicationId = @ApplicationId

END





GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_Roles_CreateUpdateDelete] to public
go
/***********************************************
* Sproc: cs_Roles_Get
* File Date: 11/29/2006 10:07:31 AM
***********************************************/
Print 'Creating...cs_Roles_Get'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Roles_Get]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Roles_Get]
GO

CREATE   procedure [dbo].cs_Roles_Get
(
@UserID int = 0,
@SettingsID int
)
AS
SET Transaction Isolation Level Read UNCOMMITTED
BEGIN

Declare @ApplicationName nvarchar(256)
Select @ApplicationName = ApplicationName from cs_SiteSettings where SettingsID = @SettingsID

DECLARE @ApplicationId UNIQUEIDENTIFIER
SELECT  @ApplicationId = NULL
SELECT  @ApplicationId = ApplicationId FROM aspnet_Applications WHERE LOWER(@ApplicationName) = LoweredApplicationName


	IF (@UserID = 0)
		SELECT
			RoleId, RoleName as [Name], Description
		FROM
			aspnet_Roles where ApplicationId = @ApplicationId
	ELSE
		SELECT DISTINCT
			R.RoleId, RoleName as [Name], Description
		FROM 
			aspnet_UsersInRoles U,
			aspnet_Roles R,
			cs_UserProfile P
		WHERE
			U.RoleId = R.RoleId AND
			P.UserID = @UserID AND
			P.MembershipID = U.UserId and P.SettingsID = @SettingsID and R.ApplicationId = @ApplicationId
END








GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_Roles_Get] to public
go
/***********************************************
* Sproc: cs_Role_Get
* File Date: 11/29/2006 10:07:31 AM
***********************************************/
Print 'Creating...cs_Role_Get'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Role_Get]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Role_Get]
GO


--We will need to filter all by application name

create procedure [dbo].cs_Role_Get
(
	@RoleID uniqueidentifier = null,
	@RoleName nvarchar(256) = null,
	@SettingsID int
	
)
AS
SET Transaction Isolation Level Read UNCOMMITTED
BEGIN


	Declare @ApplicationName nvarchar(256)
	Select @ApplicationName = ApplicationName from cs_SiteSettings where SettingsID = @SettingsID
	
	
	select RoleId, RoleName as [Name], r.Description
	from aspnet_Roles r
		inner join aspnet_Applications a on 
			r.ApplicationId = a.ApplicationId
	where
		((@RoleID is not null and r.RoleId = @RoleID ) or @RoleID is null ) and
		((@RoleName is not null and r.RoleName = @RoleName ) or @RoleName is null ) and
		a.LoweredApplicationName = lower(@ApplicationName);


END







GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO









GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_Role_Get] to public
go
/***********************************************
* Sproc: cs_RollerBlog_AddFeed
* File Date: 11/29/2006 10:07:30 AM
***********************************************/
Print 'Creating...cs_RollerBlog_AddFeed'

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_RollerBlog_AddFeed]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_RollerBlog_AddFeed]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO



CREATE        PROC [dbo].cs_RollerBlog_AddFeed
	@SectionID INT,
	@SettingsID INT,
	@FeedUrl NVARCHAR(512),
	@SiteUrl NVARCHAR(512),
    @Title NVARCHAR(512),
	@IntervalMin INT,
	@ExerptSize INT,
	@PostFullText BIT,
	@IsBlogAggregated BIT,
	@IsBlogRollAggregated BIT,
	@Enabled BIT,
	@State INT,
	@NewUrlID INT OUTPUT
AS

-- -- *** Test Data ***
-- DECLARE @SectionID INT
-- DECLARE @Url NVARCHAR(512)
-- DECLARE @Title NVARCHAR(512)
-- DECLARE @UrlId INT
-- 
-- SET @SectionID = 4 -- Sample Weblog
-- SET @Url = 'http://communityserver.org/roller/rss.ashx'
-- SET @Title = 'Community Server'
-- -- *** End Test Data ***

DECLARE @AUrlId INT
DECLARE @RecCount INT
DECLARE @CurrentDateTime DateTime
SET @CurrentDateTime = GetDate()

--Settings ID is now coming from the data layer
--DECLARE @SettingsID INT
--SET @SettingsID = (Select SettingsID FROM cs_Sections WHERE SectionID = @SectionID)

-- First, let's see if the url is already int cs_RollerBlogUrls.
SELECT @AUrlId = UrlID
FROM cs_RollerBlogUrls
WHERE Url = @FeedUrl --'http://communityserver.org/roller/rss.ashx'

-- If it's not, let's insert it and grab the FeedId.
IF (@AUrlId IS NULL)
  BEGIN
	
	-- Insert it.
	INSERT INTO cs_RollerBlogUrls
	(
		Url
	) 
	VALUES
	(
		@FeedUrl
	)

	-- Grab the identity generated.
	SELECT @AUrlId = @@IDENTITY

  END

-- Let's see if this feed is already part of cs_RollerBlogFeeds based on the SectionID and UrlId.
SET @RecCount = (SELECT COUNT(SectionID) FROM cs_RollerBlogFeeds WHERE UrlId = @AUrlId AND SectionID = @SectionID)

IF (@RecCount = 0)
BEGIN
        -- Add the feed to cs_RollerBlogFeeds based on SectionID (users blog).
	INSERT INTO cs_RollerBlogFeeds
	(
		SectionID,
		UrlId,
		SettingsId,
		SiteUrl,
        IntervalMinutes,
		Title,
		SubscribeDate,
		LastUpdateDate,
		LastModifiedDate,
		PostFullArticle,
		ExerptSize,
		IsBlogAggregated,
		IsBlogRollAggregated,
		Enabled,
		State
	)
	VALUES
	(
		@SectionID,
		@AUrlId,
		@SettingsID,
		@SiteUrl,
		@IntervalMin,
		@Title,
	    @CurrentDateTime,
	    @CurrentDateTime,
	    @CurrentDateTime,
		@PostFullText,
		@ExerptSize,
		@IsBlogAggregated,
		@IsBlogRollAggregated,
		@Enabled,
		@State
	)
END
ELSE
BEGIN
        -- Enable the already existing feed.
	UPDATE cs_RollerBlogFeeds
	SET 
		Enabled = 1, 
		IntervalMinutes = @IntervalMin, 
		Title = @Title,
		PostFullArticle = @PostFullText, 
		ExerptSize = @ExerptSize,
        IsBlogAggregated = @IsBlogAggregated, 
		IsBlogRollAggregated = @IsBlogRollAggregated, 
		SiteUrl = @SiteUrl
	WHERE UrlId = @AUrlId AND SectionID = @SectionID
END

SELECT @NewUrlID = @AUrlId



GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_RollerBlog_AddFeed] to public
go

/***********************************************
* Sproc: cs_RollerBlog_AddPost
* File Date: 11/29/2006 10:07:33 AM
***********************************************/
Print 'Creating...cs_RollerBlog_AddPost'

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_RollerBlog_AddPost]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_RollerBlog_AddPost]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO


CREATE PROC [dbo].cs_RollerBlog_AddPost
	@PostID INT,
	@SectionID INT,
	@URlId INT,
	@PermaLink NVARCHAR(512),
	@CommentsUrl NVARCHAR(512),
	@CommentsCount INT,
	@GuidName NVARCHAR(512),
	@GuidIsPermaLink BIT
AS

INSERT INTO cs_RollerBlogPost
(
	PostID,
	SectionID,
	UrlId,
	PermaLink,
	CommentUrl,
	CommentCount,
	GuidName,
	GuidIsPermaLink
)

VALUES
(
	@PostID,
	@SectionID,
	@URlId,
	@PermaLink,
	@CommentsUrl,
	@CommentsCount,
	@GuidName,
	@GuidIsPermaLink
)




GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_RollerBlog_AddPost] to public
go
/***********************************************
* Sproc: cs_RollerBlog_DeleteFeed
* File Date: 11/29/2006 10:07:31 AM
***********************************************/
Print 'Creating...cs_RollerBlog_DeleteFeed'

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_RollerBlog_DeleteFeed]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_RollerBlog_DeleteFeed]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO



CREATE  PROC [dbo].cs_RollerBlog_DeleteFeed
	@SectionID INT,
	@UrlId INT
AS

UPDATE cs_RollerBlogFeeds
SET 	LastUpdateDate = GetDate(), Enabled = 0
WHERE SectionID = @SectionID AND UrlId = @UrlId



GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_RollerBlog_DeleteFeed] to public
go

/***********************************************
* Sproc: cs_RollerBlog_GetAllEnabledFeeds
* File Date: 11/29/2006 10:07:33 AM
***********************************************/
Print 'Creating...cs_RollerBlog_GetAllEnabledFeeds'

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_RollerBlog_GetAllEnabledFeeds]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_RollerBlog_GetAllEnabledFeeds]
GO


/***********************************************
* Sproc: cs_RollerBlog_GetAllFeed
* File Date: 11/29/2006 10:07:29 AM
***********************************************/
Print 'Creating...cs_RollerBlog_GetAllFeed'

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_RollerBlog_GetAllFeeds]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_RollerBlog_GetAllFeeds]
GO


/***********************************************
* Sproc: cs_RollerBlog_GetEnabledFeedsBySectionID
* File Date: 11/29/2006 10:07:34 AM
***********************************************/
Print 'Creating...cs_RollerBlog_GetEnabledFeedsBySectionID'

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_RollerBlog_GetEnabledFeedsBySectionID]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_RollerBlog_GetEnabledFeedsBySectionID]
GO


/***********************************************
* Sproc: cs_RollerBlog_GetFeeds
* File Date: 11/29/2006 10:07:31 AM
***********************************************/
Print 'Creating...cs_RollerBlog_GetFeeds'

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_RollerBlog_GetFeeds]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_RollerBlog_GetFeeds]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO


CREATE PROC [dbo].[cs_RollerBlog_GetFeeds]
(
	@SettingsID int,
	@EnabledOnly bit = 0,
	@UpdateNeededOnly bit = 0,
	@SectionID int = 0
)
AS

SELECT
	SectionID
	,rbf.UrlId
    ,rollerUrls.Url
    ,rbf.SiteUrl
	,rbf.SettingsID
	,rbf.Enabled
    ,rbf.IntervalMinutes
	,rbf.Title
	,rbf.SubscribeDate
	,rbf.LastUpdateDate
	,rbf.LastModifiedDate
	,rbf.PostFullArticle
	,rbf.ExerptSize
	,rbf.ETag
	,rbf.IsBlogAggregated
	,rbf.IsBlogRollAggregated

FROM
	cs_RollerBlogFeeds rbf
	INNER JOIN cs_RollerBlogUrls rollerUrls on rollerUrls.UrlID = rbf.UrlId
WHERE
	SettingsID = @SettingsID
	AND (rbf.Enabled = @EnabledOnly or @EnabledOnly = 0)
	AND (SectionID = @SectionID or @SectionID = 0)
	AND (DateAdd(mi, rbf.IntervalMinutes, LastUpdateDate) <= GetDate() or @UpdateNeededOnly = 0)

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_RollerBlog_GetFeeds] to public
go

/***********************************************
* Sproc: cs_RollerBlog_GetPosts
* File Date: 11/29/2006 10:07:30 AM
***********************************************/
Print 'Creating...cs_RollerBlog_GetPosts'

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_RollerBlog_GetPosts]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_RollerBlog_GetPosts]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO



CREATE PROC [dbo].cs_RollerBlog_GetPosts
	@SectionID INT,
	@UrlId INT

AS

SELECT
	SectionID,
	UrlId,
	PostID,
	PermaLink,
	CommentUrl,
	CommentCount,
	GuidName,
	GuidIsPermaLink
FROM
	cs_RollerBlogPost
WHERE
	SectionID = @SectionID AND UrlId = @UrlId



GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_RollerBlog_GetPosts] to public
go

/***********************************************
* Sproc: cs_RollerBlog_UpdateFeed
* File Date: 11/29/2006 10:07:32 AM
***********************************************/
Print 'Creating...cs_RollerBlog_UpdateFeed'

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_RollerBlog_UpdateFeed]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_RollerBlog_UpdateFeed]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO




CREATE   PROC [dbo].cs_RollerBlog_UpdateFeed
	@SectionID INT,
	@UrlId INT,
    @FeedState INT,
   	@LastUpdateDate DateTime OUTPUT

AS

SELECT @LastUpdateDate = GetDate();
UPDATE cs_RollerBlogFeeds
SET 	
	-- we need to use the sql servers time for this
	LastUpdateDate = @LastUpdateDate, 
	State = @FeedState
WHERE SectionID = @SectionID AND UrlId = @UrlId




GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_RollerBlog_UpdateFeed] to public
go

/***********************************************
* Sproc: cs_RollerBlog_UpdatePost
* File Date: 11/29/2006 10:07:31 AM
***********************************************/
Print 'Creating...cs_RollerBlog_UpdatePost'

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_RollerBlog_UpdatePost]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_RollerBlog_UpdatePost]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO


CREATE PROC [dbo].cs_RollerBlog_UpdatePost
	@PostID INT,
	@SectionID INT,
	@URlId INT,
	@PermaLink NVARCHAR(512),
	@CommentsUrl NVARCHAR(512),
	@CommentsCount INT,
	@GuidName NVARCHAR(512),
	@GuidIsPermaLink BIT
AS

UPDATE cs_RollerBlogPost

SET
	SectionID = SectionID,
	UrlId = @URlId,
	PermaLink = @PermaLink,
	CommentUrl = @CommentsUrl,
	CommentCount = @CommentsCount,
	GuidName = @GuidName,
	GuidIsPermaLink = @GuidIsPermaLink

WHERE
	PostID = @PostID




GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_RollerBlog_UpdatePost] to public
go
/***********************************************
* Sproc: cs_Roller_AddFeed
* File Date: 11/29/2006 10:07:31 AM
***********************************************/
Print 'Creating...cs_Roller_AddFeed'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Roller_AddFeed]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Roller_AddFeed]
GO


CREATE PROC [dbo].cs_Roller_AddFeed
	@UserId INT,
	@FeedId INT
AS


INSERT INTO cs_FolderFeed
(
	UserId,
	FolderId,
	FeedId
)
VALUES
(
	@UserId,
	NULL,
	@FeedId
)


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT EXECUTE ON [dbo].cs_Roller_AddFeed  TO PUBLIC
GO

/***********************************************
* Sproc: cs_Roller_GetFeeds
* File Date: 11/29/2006 10:07:31 AM
***********************************************/
Print 'Creating...cs_Roller_GetFeeds'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Roller_GetFeeds]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Roller_GetFeeds]
GO

CREATE PROC [dbo].cs_Roller_GetFeeds
	@UserId INT
AS


SELECT 	f.FeedId,
	f.Title,
	f.Url,
	f.Link
FROM 	cs_Feed f,
	cs_FolderFeed ff
WHERE f.FeedId = ff.FeedId
  AND ff.UserId = @UserId
ORDER BY Title


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT EXECUTE ON [dbo].cs_Roller_GetFeeds  TO PUBLIC
GO

/***********************************************
* Sproc: cs_Roller_GetPosts
* File Date: 11/29/2006 10:07:30 AM
***********************************************/
Print 'Creating...cs_Roller_GetPosts'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Roller_GetPosts]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Roller_GetPosts]
GO


CREATE PROC [dbo].cs_Roller_GetPosts
	@UserID INT,
	@PageIndex int = 0, 
	@PageSize int = 25,
	@TotalRecords int output
AS

SET Transaction Isolation Level Read UNCOMMITTED

DECLARE @PageLowerBound int
DECLARE @PageUpperBound int
DECLARE @RowsToReturn int
DECLARE @TotalThreads int

-- First set the rowcount
SET @RowsToReturn = @PageSize * (@PageIndex + 1)


-- Set the page bounds
SET @PageLowerBound = @PageSize * @PageIndex
SET @PageUpperBound = @PageLowerBound + @PageSize + 1

CREATE TABLE #PageIndex 
(
	IndexID int IDENTITY (1, 1) NOT NULL,
	FeedPostId int
)

Insert #PageIndex (FeedPostId)
Select fp.FeedPostId
FROM cs_FeedPost fp,
	cs_Feed f,
	cs_FolderFeed ff
WHERE fp.FeedId = f.FeedId
  AND f.FeedId = ff.FeedId
  AND ff.UserId = @UserId
ORDER BY fp.FeedPostId DESC 
-- changed this to Id instead of date. 
-- Do all feeds return acurate dates, do we care? 
-- My guess is users want to see what was most recently added to the site.

SET @TotalRecords = @@rowcount

SELECT 	f.Title AS 'FeedTitle',
	f.Link AS 'FeedLink',
	fp.FeedPostId,
	fp.FeedId,
	fp.Author,
	fp.Title,
	fp.Description,
	fp.Source,
	fp.GuidName,
	fp.GuidIsPermaLink,
	fp.Link,
	fp.PubDate,
	fp.CommentsUrl,
	fp.EnclosureUrl,
	fp.EnclosureLength,
	fp.EnclosureType,
	fp.Creator,
	fp.CommentApiUrl,
	fp.CommentRssUrl,
	fp.CommentCount
FROM cs_FeedPost fp,
	cs_Feed f,
	cs_FolderFeed ff,
	#PageIndex fPI
WHERE fp.FeedId = f.FeedId
  AND f.FeedId = ff.FeedId
  AND ff.UserId = @UserId
  AND fPI.FeedPostID = fp.FeedPostID
  AND fPI.IndexID > @PageLowerBound
  AND fPI.IndexID < @PageUpperBound
ORDER BY fPI.IndexID


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT EXECUTE ON [dbo].cs_Roller_GetPosts  TO PUBLIC
GO

/***********************************************
* Sproc: cs_Roller_GetUnaggregatedFeeds
* File Date: 11/29/2006 10:07:30 AM
***********************************************/
Print 'Creating...cs_Roller_GetUnaggregatedFeeds'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Roller_GetUnaggregatedFeeds]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Roller_GetUnaggregatedFeeds]
GO


CREATE PROC [dbo].cs_Roller_GetUnaggregatedFeeds
	@UserID INT
AS

SELECT  FeedId,
	Url,
	Title,
	Link,
	Language,
	Generator,
	SubscribeDate,
	LastUpdateDate,
	FeedStateId,
	LastModified,
	ETag
FROM cs_Feed
WHERE FeedId NOT IN (
	SELECT FeedId
	FROM cs_FolderFeed
	WHERE UserId = @UserId
	AND FolderId IS NULL
)
ORDER BY Title ASC



GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT EXECUTE ON [dbo].cs_Roller_GetUnaggregatedFeeds  TO PUBLIC
GO

/***********************************************
* Sproc: cs_SearchBarrel_Search
* File Date: 11/29/2006 10:07:31 AM
***********************************************/
Print 'Creating...cs_SearchBarrel_Search'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_SearchBarrel_Search]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_SearchBarrel_Search]
GO





CREATE procedure dbo.cs_SearchBarrel_Search (
	@SearchSQL NText,
	--@RecordCountSQL nvarchar(4000),
	@PageIndex int = 0,
	@PageSize int = 25,
	@SettingsID int
)
AS
SET Transaction Isolation Level Read UNCOMMITTED
BEGIN

	DECLARE @StartTime datetime
	DECLARE @RowsToReturn int
	DECLARE @PageLowerBound int
	DECLARE @PageUpperBound int
	DECLARE @Count int
	DECLARE @TotalRecords int

	-- Used to calculate cost of query
	SET @StartTime = GetDate()

	-- Set the rowcount
	SET @RowsToReturn = @PageSize * (@PageIndex + 1)
	--SET ROWCOUNT @RowsToReturn

	-- Calculate the page bounds
	SET @PageLowerBound = @PageSize * @PageIndex
	SET @PageUpperBound = @PageLowerBound + @PageSize + 1

	-- Create a temp table to store the results in
	CREATE TABLE #SearchResults
	(
		IndexID int IDENTITY (1, 1) NOT NULL,
		PostID int,
		SectionID int,
		Weight int,
		PostDate datetime
	)

	-- Fill the temp table
	INSERT INTO #SearchResults (PostID, SectionID, Weight, PostDate)
	exec (@SearchSQL)

	SET @TotalRecords = @@rowcount

	SET ROWCOUNT @RowsToReturn

	-- SELECT actual search results from this table
	SELECT
		P.PostID, P.ThreadID, P.ParentID, P.PostAuthor, P.UserID, P.SectionID, P.Subject, P.PostDate,
		P.FormattedBody, P.IPAddress, P.PostType, P.SettingsID, P.UserTime,
		P.ApplicationPostType, P.PostName, P.UserTime,
		AttachmentFilename =  ISNULL ( (SELECT [FileName] FROM cs_PostAttachments WHERE PostID = P.PostID), ''),
		S.ApplicationKey, S.GroupID, S.ApplicationType, S.Name as SectionName

	FROM 
		cs_Posts P,
		cs_Sections S,
		#SearchResults R
	WHERE
		P.PostID = R.PostID AND
		P.SectionID = S.SectionID AND
		R.IndexID > @PageLowerBound AND
		R.IndexID < @PageUpperBound AND
		P.SettingsID = @SettingsID
	Order By IndexID

	DROP Table #SearchResults

	Select @TotalRecords

	SELECT Duration = GetDate() - @StartTime
END



GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT  EXECUTE  ON [dbo].[cs_SearchBarrel_Search]  TO [public]
GO


/***********************************************
* Sproc: cs_Search_Add
* File Date: 11/29/2006 10:07:31 AM
***********************************************/
Print 'Creating...cs_Search_Add'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Search_Add]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Search_Add]
GO




CREATE  procedure [dbo].cs_Search_Add (
	@WordHash int,
	@Word nvarchar(64),
	@Weight float,
	@PostID int,
	@ThreadID int,
	@SectionID int,
	@SettingsID int
)
AS
SET Transaction Isolation Level Read UNCOMMITTED
BEGIN
	IF EXISTS (SELECT WordHash FROM cs_SearchBarrel WHERE PostID = @PostID AND WordHash = @WordHash)
		UPDATE 
			cs_SearchBarrel 
		SET
			Weight = @Weight
		WHERE
			WordHash = @WordHash AND
			PostID = @PostID and SettingsID = @SettingsID
	ELSE
		INSERT INTO
			cs_SearchBarrel
			(WordHash, Word, PostID, ThreadID, SectionID, Weight, SettingsID)
		VALUES
			(@WordHash, @Word, @PostID, @ThreadID, @SectionID, @Weight, @SettingsID)

	IF EXISTS (SELECT PostID From cs_Posts WHERE PostID = @PostID AND IsIndexed = 0 and SettingsID = @SettingsID)
		UPDATE cs_Posts SET IsIndexed = 1 WHERE PostID = @PostID and SettingsID = @SettingsID

END







GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_Search_Add] to public
go
/***********************************************
* Sproc: cs_Search_IgnoreWords
* File Date: 11/29/2006 10:07:30 AM
***********************************************/
Print 'Creating...cs_Search_IgnoreWords'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Search_IgnoreWords]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Search_IgnoreWords]
GO




CREATE   procedure [dbo].cs_Search_IgnoreWords
(
	@SettingsID int
)
AS
SET Transaction Isolation Level Read UNCOMMITTED
BEGIN
		SELECT
			WordHash,
			Word
		FROM
			cs_SearchIgnoreWords
		WHERE
			SettingsID = @SettingsID
END






GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_Search_IgnoreWords] to public
go
/***********************************************
* Sproc: cs_Search_IgnoreWords_CreateDelete
* File Date: 11/29/2006 10:07:32 AM
***********************************************/
Print 'Creating...cs_Search_IgnoreWords_CreateDelete'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Search_IgnoreWords_CreateDelete]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Search_IgnoreWords_CreateDelete]
GO





create procedure [dbo].cs_Search_IgnoreWords_CreateDelete
(
	@WordHash int,
	@Word nvarchar (64),
	@Action int,
	@SettingsID int
)
AS
SET Transaction Isolation Level Read UNCOMMITTED
-- CREATE
IF @Action = 0
BEGIN
IF NOT EXISTS(SELECT * FROM cs_SearchIgnoreWords WHERE WordHash = @WordHash)
	INSERT INTO 
		cs_SearchIgnoreWords
	VALUES
		(@WordHash, @Word, @SettingsID)
END

-- DELETE
ELSE IF @Action = 2
BEGIN
	DELETE 
		cs_SearchIgnoreWords 
	WHERE 
		WordHash = @WordHash and SettingsID = @SettingsID

	DELETE
		cs_SearchBarrel
	WHERE
		WordHash = @WordHash and SettingsID = @SettingsID
END






GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_Search_IgnoreWords_CreateDelete] to public
go
/***********************************************
* Sproc: cs_Search_PostReindex
* File Date: 11/29/2006 10:07:32 AM
***********************************************/
Print 'Creating...cs_Search_PostReindex'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Search_PostReindex]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Search_PostReindex]
GO




/***********************************************
* Sproc: cs_Search_UpdatePostIndexStatus
* File Date: 11/29/2006 10:07:31 AM
***********************************************/
Print 'Creating...cs_Search_UpdatePostIndexStatus'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Search_UpdatePostIndexStatus]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Search_UpdatePostIndexStatus]
GO




CREATE  procedure [dbo].cs_Search_UpdatePostIndexStatus (
	@PostID int,
	@SettingsID int,
	@Status bit = 1
)
AS
SET Transaction Isolation Level Read UNCOMMITTED
BEGIN
	UPDATE cs_Posts SET IsIndexed = @Status WHERE PostID = @PostID and SettingsID = @SettingsID
END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_Search_UpdatePostIndexStatus] to public
go
/***********************************************
* Sproc: cs_Sections_Get
* File Date: 11/29/2006 10:07:30 AM
***********************************************/
Print 'Creating...cs_Sections_Get'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Sections_Get]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Sections_Get]
GO


CREATE PROCEDURE [dbo].cs_Sections_Get
(
	@SettingsID				int,
	@ApplicationType        smallint = 0,
	@AllowInactive			bit = 0,
	@IncludePostTypeCounts	bit = 0
)
AS
SET Transaction Isolation Level Read UNCOMMITTED
-- Return all the forums
SELECT  
	F.SectionID, F.SettingsID, F.IsActive, F.ParentID, F.GroupID, F.Name, F.NewsgroupName, F.Description, F.DateCreated, F.Url, F.IsModerated,
	F.DaysToView, F.SortOrder, F.TotalPosts, F.TotalThreads, F.DisplayMask, F.EnablePostStatistics, F.EnablePostPoints, F.EnableAutoDelete, F.EnableAnonymousPosting,
	F.AutoDeleteThreshold, F.MostRecentPostID, F.MostRecentThreadID, F.MostRecentThreadReplies, F.MostRecentPostSubject, F.MostRecentPostAuthor,
	F.MostRecentPostAuthorID, F.MostRecentPostDate, F.PostsToModerate, F.ForumType, F.IsSearchable, F.ApplicationType, F.ApplicationKey, F.Path,
	F.PropertyNames as SectionPropertyNames, F.PropertyValues as SectionPropertyValues, F.DefaultLanguage, F.DiskUsage

FROM
	cs_Sections F
WHERE
	SettingsID = @SettingsID AND
	--(IsActive = 1 OR 1 = @AllowInactive) AND
	 ApplicationType = @ApplicationType

--Declare @AnonID int
--exec cs_GetAnonymousUserID @SettingsID, @AnonID output

exec cs_Section_Permissions_Get @SettingsID, 0, @ApplicationType

--Return the counts of each post type
IF @IncludePostTypeCounts > 0
BEGIN
	SELECT 
		F.ApplicationKey, P.ApplicationPostType, Count(*) as PostCount
	FROM 
		cs_Sections F
		JOIN cs_Posts P on F.SectionID = P.SectionID
	WHERE
		F.SettingsID = @SettingsID AND
		F.ApplicationType = @ApplicationType
	GROUP BY F.ApplicationKey, P.ApplicationPostType
END
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT  EXECUTE  ON [dbo].[cs_Sections_Get]  TO [public]
GO


/***********************************************
* Sproc: cs_Sections_GetRead
* File Date: 11/29/2006 10:07:34 AM
***********************************************/
Print 'Creating...cs_Sections_GetRead'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Sections_GetRead]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Sections_GetRead]
GO


create procedure [dbo].cs_Sections_GetRead (
	@UserID as int,
	@SettingsID as int
)
AS
SET Transaction Isolation Level Read UNCOMMITTED
SELECT 
	SectionID,
	LastActivity
FROM
	cs_SectionsRead
WHERE
	UserID = @UserID AND 
	SettingsID = @SettingsID

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_Sections_GetRead] to public
go
/***********************************************
* Sproc: cs_Sections_MoveOrReOrder
* File Date: 11/29/2006 10:07:31 AM
***********************************************/
Print 'Creating...cs_Sections_MoveOrReOrder'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Sections_MoveOrReOrder]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Sections_MoveOrReOrder]
GO

Create Proc [dbo].cs_Sections_MoveOrReOrder
(
	@NewGroupID int,
	@SectionID int,
	@SectionIndex int,
	@SettingsID int
)

as

Declare @OldGroupId int
Select @OldGroupId = GroupID from cs_Sections where SectionID = @SectionID and SettingsID = @SettingsID

if(@NewGroupID <> @OldGroupId) -- move from one group to another
Begin
	--Move the group, mark order at the end
	update cs_Sections
	Set GroupID = @NewGroupID, SortOrder = 9999999 where SectionID = @SectionID and SettingsID = @SettingsID

	--Update Old Group
	exec cs_Sections_ResetOrder @OldGroupId, @SettingsID
End

--Reset the Section
exec cs_Section_MoveSection @NewGroupID, @SectionID, @SectionIndex, @SettingsID


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_Sections_MoveOrReOrder] to public
go
/***********************************************
* Sproc: cs_Sections_ResetOrder
* File Date: 11/29/2006 10:07:31 AM
***********************************************/
Print 'Creating...cs_Sections_ResetOrder'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Sections_ResetOrder]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Sections_ResetOrder]
GO

Create Proc [dbo].cs_Sections_ResetOrder
(
	@GroupID int,
	@SettingsID int
)
as

Declare @Sort int
Set @Sort = 0
Declare @SectionID int
DECLARE section_Cursor CURSOR FOR
SELECT SectionID FROM cs_Sections where GroupID = @GroupID and SettingsID = @SettingsID order by SortOrder

OPEN section_Cursor

FETCH NEXT FROM section_Cursor Into @SectionID
WHILE (@@FETCH_STATUS = 0)
Begin
	Update cs_Sections Set SortOrder = @Sort where SectionID = @SectionID
	Set @Sort = @Sort + 1
   FETCH NEXT FROM section_Cursor Into @SectionID
End

CLOSE section_Cursor
DEALLOCATE section_Cursor


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_Sections_ResetOrder] to public
go
/***********************************************
* Sproc: cs_SectionTokens_Add
* File Date: 11/29/2006 10:07:32 AM
***********************************************/
Print 'Creating...cs_SectionTokens_Add'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_SectionTokens_Add]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_SectionTokens_Add]
GO

Create Proc [dbo].[cs_SectionTokens_Add]
(
	@Token nvarchar(50),
	@Link nvarchar(255) = null,
	@Text nvarchar(500),
	@SettingsID int,
	@SectionID int,
	@TokenID int output
)

as

Insert cs_SectionTokens (Token, Link, [Text], SettingsID, SectionID)
Values (@Token, @Link, @Text, @SettingsID, @SectionID)

Select @TokenID = @@Identity



GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].cs_SectionTokens_Add to public
go
/***********************************************
* Sproc: cs_SectionTokens_Delete
* File Date: 11/29/2006 10:07:31 AM
***********************************************/
Print 'Creating...cs_SectionTokens_Delete'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_SectionTokens_Delete]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_SectionTokens_Delete]
GO


Create Proc [dbo].[cs_SectionTokens_Delete]
(
	@TokenID int,
	@SectionID int,
	@SettingsID int
)
as
Delete FROM cs_SectionTokens where TokenID = @TokenID and SettingsID = @SettingsID and SectionID = @SectionID


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].cs_SectionTokens_Delete to public
go
/***********************************************
* Sproc: cs_SectionTokens_Get
* File Date: 11/29/2006 10:07:31 AM
***********************************************/
Print 'Creating...cs_SectionTokens_Get'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_SectionTokens_Get]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_SectionTokens_Get]
GO

Create Proc [dbo].[cs_SectionTokens_Get]
(
	@SectionID int,
	@SettingsID int
)
as
Select TokenID, Token, Link, [Text], SectionID FROM cs_SectionTokens where SettingsID = @SettingsID and SectionID = @SectionID Order by Token


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].cs_SectionTokens_Get to public
go
/***********************************************
* Sproc: cs_SectionTokens_Update
* File Date: 11/29/2006 10:07:31 AM
***********************************************/
Print 'Creating...cs_SectionTokens_Update'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_SectionTokens_Update]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_SectionTokens_Update]
GO

Create Proc [dbo].[cs_SectionTokens_Update]
(
	@TokenID int,
	@Token nvarchar(50),
	@Link nvarchar(255) = null,
	@Text nvarchar(500),
	@SettingsID int,
	@SectionID int
)

as

update cs_SectionTokens
Set 
	Token = @Token,
	Link = @Link,
	[Text] = @Text
where
	TokenID = @TokenID and SettingsID = @SettingsID and SectionID = @SectionID




GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].cs_SectionTokens_Update to public
go
/***********************************************
* Sproc: cs_Section_CreateUpdateDelete
* File Date: 11/29/2006 10:07:31 AM
***********************************************/
Print 'Creating...cs_Section_CreateUpdateDelete'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Section_CreateUpdateDelete]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Section_CreateUpdateDelete]
GO


-- sp_helptext cs_Section_CreateUpdateDelete


CREATE PROCEDURE [dbo].cs_Section_CreateUpdateDelete
(
	@SectionID	int out,
	@DeleteForum	bit = 0,
	@Name		nvarchar(256) = '',
	@Url		nvarchar(512) = '',
	@Description	nvarchar(3000) = '',
	@ParentID	int = 0,
	@SettingsID	int,
	@GroupID	int = 0,
	@IsModerated	bit = 1,
	@IsSearchable   bit = 1,
	@DisplayPostsOlderThan	int = 0,
	@IsActive 	bit = 0,
	@EnablePostStatistics bit = 1,
	@EnablePostPoints bit = 1,
	@EnableAutoDelete bit = 0,
	@EnableAnonymousPosting bit = 0,
	@AutoDeleteThreshold int = 90,
	@SortOrder int = 0,
	@PropertyNames ntext = null,
	@PropertyValues ntext = null,
	@ApplicationKey nvarchar(256) = null,
	@ApplicationType smallint = 0,
	@ForumType int = 0,
	@UserID int,
	@DefaultLanguage nvarchar(32) = null
)
AS
SET Transaction Isolation Level Read UNCOMMITTED
-- Are we deleting the forum?
IF @DeleteForum = 1
BEGIN

	Select @ApplicationKey = 'Deleted Section ' + ApplicationKey FROM cs_Sections where SectionID = @SectionID and SettingsID = @SettingsID

	exec cs_system_ModerationAction_AuditEntry 19, @UserID, null, @UserID, @SectionID, @SettingsID,  @ApplicationKey


           DECLARE @SectionToDeleteParentID int
           SET @SectionToDeleteParentID = (SELECT ParentID FROM cs_Sections WHERE SectionID = @SectionID)

	-- delete the specified forum and all of its posts
	-- first we must remove all the thread tracking rows
	DELETE 
		cs_TrackedThreads
	WHERE 
		ThreadID IN (SELECT DISTINCT ThreadID FROM cs_Threads WHERE SectionID = @SectionID and SettingsID = @SettingsID)

	-- we must remove all of the moderators for this forum
	DELETE 
		cs_Moderators
	WHERE 
		SectionID = @SectionID and SettingsID = @SettingsID

	-- we must remove all roller blog related data
	DELETE
		cs_RollerBlogPost
	FROM
		cs_RollerBlogPost RBP INNER JOIN cs_RollerBlogFeeds RBF ON  RBP.SectionID = RBF.SectionID AND RBP.UrlID = RBF.UrlID
	WHERE
		RBF.SectionID = @SectionID AND RBF.SettingsID = @SettingsID

	DELETE
		cs_RollerBlogFeeds
	WHERE
		SectionID = @SectionID and SettingsID = @SettingsID

	-- now we must remove all of the posts
	DELETE 
		cs_Posts
	WHERE 
		SectionID = @SectionID and SettingsID = @SettingsID

	DELETE cs_weblog_Weblogs Where SectionID = @SectionID and SettingsID = @SettingsID

	-- remove all the explicit forum permissions
	DELETE
		cs_SectionPermissions
	WHERE
		SectionID = @SectionID and SettingsID = @SettingsID

	-- finally we can delete the actual forum
	DELETE 
		cs_Sections
	WHERE 
		SectionID = @SectionID and SettingsID = @SettingsID

	DELETE 
		cs_Posts_InCategories
	WHERE
		CategoryID in (Select CategoryID FROM cs_Post_Categories where SectionID = @SectionID and SettingsID = @SettingsID)

	DELETE 
		cs_Post_Categories
	WHERE
		SectionID = @SectionID and SettingsID = @SettingsID		

	-- Clean up an child sectoins
       UPDATE
		cs_Sections
	SET 
		ParentID = @SectionToDeleteParentID
        WHERE
                ParentID = @SectionID


	RETURN
END

-- Are we updating a forum
IF @SectionID > 0
BEGIN
	-- if we are making the forum non-moderated, remove all forum moderators for this forum
	IF @IsModerated = 0
		DELETE 
			cs_Moderators
		WHERE 
			SectionID = @SectionID and SettingsID = @SettingsID

	-- Update the forum information
	UPDATE 
		cs_Sections 
	SET
		Name = @Name,
		Url = @Url,
		Description = @Description,
		ParentID = @ParentID,
		SettingsID = @SettingsID,
		GroupID = @GroupID,
		IsModerated = @IsModerated,
		IsActive = @IsActive,
		IsSearchable = @IsSearchable,
		DaysToView = @DisplayPostsOlderThan,
		EnablePostStatistics = @EnablePostStatistics,
		EnablePostPoints = @EnablePostPoints,
		EnableAutoDelete = @EnableAutoDelete,
		EnableAnonymousPosting = @EnableAnonymousPosting,
		AutoDeleteThreshold = @AutoDeleteThreshold,
		SortOrder = @SortOrder,
		ApplicationKey = @ApplicationKey,
		ApplicationType = @ApplicationType,
		ForumType = @ForumType,
		PropertyNames = @PropertyNames,
		PropertyValues = @PropertyValues,
		DefaultLanguage = @DefaultLanguage
	WHERE 
		SectionID = @SectionID and SettingsID = @SettingsID
END
ELSE
BEGIN

	if( @SortOrder = 0 ) 
	begin
		select @SortOrder = coalesce(max(SortOrder) + 1, 1) from cs_Sections where GroupID = @GroupID

		if(@SortOrder is null)
		Begin
			Select @SortOrder = 1
		End
	end

	-- Create a new Forum
	INSERT INTO 
		cs_Sections (
			Name, 
			Url,
			Description, 
			ParentID, 
			SettingsID, 
			GroupID, 
			IsModerated, 
			DaysToView, 
			IsActive,
			IsSearchable,
			EnablePostStatistics,
			EnablePostPoints,
			EnableAutoDelete,
			AutoDeleteThreshold,
			SortOrder,
			ApplicationKey,
			ApplicationType,
			ForumType,
			PropertyNames,
			PropertyValues,
			DefaultLanguage
			)
		VALUES (
			@Name,
			@Url,
			@Description,
			@ParentID,
			@SettingsID,
			@GroupID,
			@IsModerated,
			@DisplayPostsOlderThan,
			@IsActive,
			@IsSearchable,
			@EnablePostStatistics,
			@EnablePostPoints,
			@EnableAutoDelete,
			@AutoDeleteThreshold,
			@SortOrder,
			@ApplicationKey, 
			@ApplicationType,
			@ForumType,
			@PropertyNames,
			@PropertyValues,
			@DefaultLanguage
			)
	
	SET @SectionID = @@Identity

	If @ApplicationType = 1
	Begin
		Insert cs_weblog_Weblogs (SectionID, SettingsID) Values (@SectionID, @SettingsID)
	End

END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT  EXECUTE  ON [dbo].[cs_Section_CreateUpdateDelete]  TO [public]
GO


/***********************************************
* Sproc: cs_Section_DiskUsage_Update
* File Date: 11/29/2006 10:07:30 AM
***********************************************/
Print 'Creating...cs_Section_DiskUsage_Update'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Section_DiskUsage_Update]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Section_DiskUsage_Update]
GO

CREATE PROCEDURE dbo.cs_Section_DiskUsage_Update
(
	@SectionID int,
	@SettingsID int
)
AS
SET Transaction Isolation Level Read UNCOMMITTED
BEGIN

	UPDATE cs_Sections SET DiskUsage = (SELECT COALESCE(SUM(Convert(bigint, ContentSize)),0) AS DiskUsage FROM cs_PostAttachments WHERE SectionID = @SectionID AND SettingsID = @SettingsID)
	WHERE SettingsID = @SettingsID AND SectionID = @SectionID
	RETURN 
END
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_Section_DiskUsage_Update] to public
go

/***********************************************
* Sproc: cs_Section_Get
* File Date: 11/29/2006 10:07:32 AM
***********************************************/
Print 'Creating...cs_Section_Get'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Section_Get]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Section_Get]
GO



CREATE Procedure [dbo].cs_Section_Get
(
	@SettingsID int,
	@SectionID int,
	@ApplicationKey nvarchar(512) = null,
	@ApplicationType smallint
)

as
SET Transaction Isolation Level Read UNCOMMITTED

if(@ApplicationKey is not null)
Begin
	Select @SectionID = SectionID FROM cs_Sections where ApplicationKey = @ApplicationKey and ApplicationType = @ApplicationType
End

SELECT 
	SectionID, SettingsID, IsActive, ParentID, GroupID, [Name], NewsgroupName, [Description], 
	DateCreated, Url, IsModerated, DaysToView, SortOrder, TotalPosts, TotalThreads, DisplayMask, 
	EnablePostStatistics, EnablePostPoints, EnableAutoDelete, EnableAnonymousPosting, AutoDeleteThreshold, 
	MostRecentPostID, MostRecentThreadID, MostRecentThreadReplies, MostRecentPostSubject, 
	MostRecentPostAuthor, MostRecentPostAuthorID, MostRecentPostDate, PostsToModerate, ForumType, 
	IsSearchable, ApplicationType, ApplicationKey, PropertyNames as SectionPropertyNames, PropertyValues as SectionPropertyValues, Path, DefaultLanguage
FROM 
	cs_Sections 
Where SectionID = @SectionID and ApplicationType = @ApplicationType

exec cs_Section_Permissions_Get @SettingsID, @SectionID, @ApplicationType
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT  EXECUTE  ON [dbo].[cs_Section_Get]  TO [public]
GO


/***********************************************
* Sproc: cs_Section_GetRandomSectionID
* File Date: 11/29/2006 10:07:33 AM
***********************************************/
Print 'Creating...cs_Section_GetRandomSectionID'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Section_GetRandomSectionID]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Section_GetRandomSectionID]
GO

CREATE PROCEDURE dbo.cs_Section_GetRandomSectionID
	@SettingsID int,
	@ApplicationType smallint,
	@AllowEmpty bit = 0
AS
SET Transaction Isolation Level Read UNCOMMITTED
select top 1 SectionID
	from cs_Sections
	where ApplicationType = @ApplicationType
		and SettingsID = @SettingsID
		and IsActive = 1
		and (TotalThreads > 0 OR 1 = @AllowEmpty)
	order by newid()

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_Section_GetRandomSectionID] to public
go
/***********************************************
* Sproc: cs_Section_GetSectionIDByPostID
* File Date: 11/29/2006 10:07:31 AM
***********************************************/
Print 'Creating...cs_Section_GetSectionIDByPostID'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Section_GetSectionIDByPostID]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Section_GetSectionIDByPostID]
GO









CREATE PROCEDURE [dbo].cs_Section_GetSectionIDByPostID
(
	@PostID			int = 0,
	@SettingsID 		int
)
AS
SET Transaction Isolation Level Read UNCOMMITTED
-- Loop up the forum by PostID

SELECT SectionID FROM cs_Posts WHERE PostID = @PostID and SettingsID = @SettingsID












GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_Section_GetSectionIDByPostID] to public
go
/***********************************************
* Sproc: cs_Section_MarkRead
* File Date: 11/29/2006 10:07:31 AM
***********************************************/
Print 'Creating...cs_Section_MarkRead'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Section_MarkRead]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Section_MarkRead]
GO




CREATE    procedure [dbo].cs_Section_MarkRead
(
	@UserID int,
	@SectionID int = 0,
	@SettingsID int,
	@GroupID int = 0,
	@MarkAllThreadsRead bit = 0

)
AS
SET Transaction Isolation Level Read UNCOMMITTED
BEGIN
DECLARE @LastReadThread int

	SET NOCOUNT ON

	IF @UserID = 0
		RETURN

	-- Are we marking all forums as read?
	IF @GroupID = 0 AND @SectionID = 0
	BEGIN

		-- 1. Delete any entries for this user
		DELETE cs_SectionsRead WHERE UserID = @UserID and SettingsID = @SettingsID
		DELETE cs_ThreadsRead WHERE UserID = @UserID and SettingsID = @SettingsID

		-- 2. INSERT into cs_SectionsRead
		INSERT INTO cs_SectionsRead
		SELECT GroupID, SectionID, @UserID, 0, 0, GetDate(), SettingsID FROM cs_Sections F WHERE SettingsID = @SettingsID

		RETURN
	END

	-- Are we marking a particular forum group as read?
	IF @GroupID > 0 AND @SectionID = 0
	BEGIN

		-- 1. Delete any entries for this user
		DELETE cs_SectionsRead WHERE UserID = @UserID AND GroupID = @GroupID and SettingsID = @SettingsID
		DELETE cs_ThreadsRead WHERE UserID = @UserID AND GroupID = @GroupID and SettingsID = @SettingsID

		-- 2. Insert into cs_Sections Read
		INSERT INTO cs_SectionsRead
		SELECT GroupID, SectionID, @UserID, 0, 0, GetDate(), SettingsID FROM cs_Sections F WHERE GroupID = @GroupID and SettingsID = @SettingsID

		RETURN
	END

	-- Are we marking an individual forum as read?
	IF @SectionID > 0
	BEGIN
		IF @MarkAllThreadsRead = 1
			IF EXISTS (SELECT UserID FROM cs_SectionsRead WHERE UserID = @UserID AND SectionID = @SectionID)
				UPDATE 
					cs_SectionsRead 
				SET 
					NewPosts = 0,
					MarkReadAfter = (SELECT (MostRecentPostID + 1) FROM cs_Sections F WHERE SectionID = @SectionID),
					LastActivity = GetDate()
				WHERE
					UserID = @UserID AND
					SectionID = @SectionID  and SettingsID = @SettingsID
			ELSE
				INSERT INTO 
					cs_SectionsRead
				SELECT GroupID, SectionID, @UserID, (MostRecentPostID + 1), 0, GetDate(), SettingsID FROM cs_Sections F WHERE SectionID = @SectionID  and SettingsID = @SettingsID
		ELSE
			IF (SELECT NewPosts FROM cs_SectionsRead WHERE UserID = @UserID AND SectionID = @SectionID) = 1
				UPDATE
					cs_SectionsRead							
				SET 
					NewPosts = 0
				WHERE
					UserID = @UserID AND
					SectionID = @SectionID

	END
END






GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_Section_MarkRead] to public
go
/***********************************************
* Sproc: cs_Section_MoveSection
* File Date: 11/29/2006 10:07:32 AM
***********************************************/
Print 'Creating...cs_Section_MoveSection'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Section_MoveSection]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Section_MoveSection]
GO

Create Proc [dbo].cs_Section_MoveSection
(
	@GroupID int,
	@SectionID int,
	@SectionIndex int,
	@SettingsID int
)

as

Set NoCount On

--Set Order
exec cs_Sections_ResetOrder @GroupID, @SettingsID

--Update all items at or below the updatedindex
update cs_Sections
Set SortOrder = SortOrder + 1 where SortOrder >= @SectionIndex and GroupID = @GroupID and SettingsID = @SettingsID

--Set the item we are updating
update cs_Sections
Set SortOrder = @SectionIndex where SectionID = @SectionID and SettingsID = @SettingsID

-- Make sure everything is sorted correctly
exec cs_Sections_ResetOrder @GroupID, @SettingsID



GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_Section_MoveSection] to public
go
/***********************************************
* Sproc: cs_Section_Permissions_Get
* File Date: 11/29/2006 10:07:31 AM
***********************************************/
Print 'Creating...cs_Section_Permissions_Get'

-- exec cs_Section_Permissions_Get 1000, 0
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from sysobjects where id = object_id(N'[dbo].[cs_Section_Permissions_Get]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Section_Permissions_Get]
GO

create procedure [dbo].cs_Section_Permissions_Get
(
	@SettingsID int,
	@SectionID int = 0,
	@ApplicationType smallint
)
AS


SET Transaction Isolation Level Read UNCOMMITTED

IF ( @SectionID = 0 ) 
	-- Return product permissions
	SELECT
		P.SettingsID, 
		Implied = convert(bit, 1), 
		SectionID = -1, 
		ApplicationKey = null,
		R.RoleName, 
		P.RoleID, 
		AllowMask = convert(bigint, coalesce(P.AllowMask, 0x00)), 
		DenyMask = convert(bigint, coalesce(P.DenyMask, 0x00)) 
	FROM
		cs_ProductPermissions P,
		aspnet_Roles R
	WHERE 
		P.RoleID = R.RoleId AND
		P.ApplicationType = @ApplicationType AND
		P.SettingsID = @SettingsID

	UNION

	-- Return section permissions
	SELECT
		P.SettingsID, 
		Implied = convert(bit, 0), 
		P.SectionID, 
		F.ApplicationKey,
		R.RoleName, 
		P.RoleID, 
		AllowMask = convert(bigint, coalesce(P.AllowMask, 0x00)),  
		DenyMask = convert(bigint, coalesce(P.DenyMask, 0x00))  
	FROM 
		cs_sectionpermissions P,
		aspnet_Roles r,
		cs_Sections F
	WHERE
		P.RoleID = r.RoleId AND
		P.SettingsID = @SettingsID AND
		P.SectionID = F.SectionID AND
		F.ApplicationType = @ApplicationType AND
		P.SettingsID = @SettingsID

ELSE IF (@SectionID > 0)
 
	-- Return product permissions
	SELECT
		P.SettingsID, 
		Implied = convert(bit, 1), 
		SectionID = -1, 
		ApplicationKey = null,
		R.RoleName, 
		P.RoleID, 
		AllowMask = convert(bigint, coalesce(P.AllowMask, 0x00)), 
		DenyMask = convert(bigint, coalesce(P.DenyMask, 0x00)) 
	FROM
		cs_ProductPermissions P,
		aspnet_Roles R
	WHERE 
		P.RoleID = R.RoleId AND
		P.ApplicationType = @ApplicationType AND
		P.SettingsID = @SettingsID

	UNION
	
	-- Return section permissions
	SELECT
		P.SettingsID, 
		Implied = convert(bit, 0), 
		P.SectionID, 
		F.ApplicationKey,
		R.RoleName, 
		P.RoleID, 
		AllowMask = convert(bigint, coalesce(P.AllowMask, 0x00)),  
		DenyMask = convert(bigint, coalesce(P.DenyMask, 0x00))  
	FROM 
		cs_sectionpermissions P,
		aspnet_Roles r,
		cs_Sections F
	WHERE
		P.RoleID = r.RoleId AND
		P.SettingsID = @SettingsID  AND
		P.SectionID = @SectionID  AND
		P.SectionID = F.SectionID AND
		F.ApplicationType = @ApplicationType AND
		P.SettingsID = @SettingsID
	
ELSE

	-- Return product permissions
	SELECT
		P.SettingsID, 
		Implied = convert(bit, 1), 
		SectionID = -1, 
		R.RoleName, 
		R.RoleId, 
		AllowMask = convert(bigint, coalesce(P.AllowMask, 0x00)), 
		DenyMask = convert(bigint, coalesce(P.DenyMask, 0x00)) 
	FROM		
		aspnet_Roles R
		inner join aspnet_Applications A on R.ApplicationId = A.ApplicationId
		inner join cs_SiteSettings ss on A.ApplicationName = ss.ApplicationName
		left outer join cs_ProductPermissions P on P.RoleID = R.RoleId and P.ApplicationType = @ApplicationType and P.SettingsID = @SettingsID
	WHERE 
		
		ss.SettingsID = @SettingsID


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_Section_Permissions_Get] to public
go
/***********************************************
* Sproc: cs_Section_Permission_CreateUpdateDelete
* File Date: 11/29/2006 10:07:30 AM
***********************************************/
Print 'Creating...cs_Section_Permission_CreateUpdateDelete'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Section_Permission_CreateUpdateDelete]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Section_Permission_CreateUpdateDelete]
GO

CREATE  procedure [dbo].cs_Section_Permission_CreateUpdateDelete
(
	@SettingsID 	int,
	@SectionID 	int,
	@RoleID		uniqueidentifier,
	@Action		int,
	@AllowMask	bigint,
	@DenyMask	bigint,
	@ApplicationType smallint
)
AS
SET Transaction Isolation Level Read UNCOMMITTED
BEGIN

-- Create
IF @Action = 0
BEGIN

	if( @SectionID <> -1 ) 
	begin
		-- Check if an entry already exists
		IF EXISTS (SELECT SectionID FROM cs_SectionPermissions WHERE SectionID = @SectionID AND RoleID = @RoleID )
			exec cs_Section_Permission_CreateUpdateDelete @SettingsID, @SectionID, @RoleID, 1, @AllowMask, @DenyMask, @ApplicationType
		ELSE
			INSERT INTO 
				cs_SectionPermissions (SettingsID, SectionID, RoleID, AllowMask, DenyMask)
			VALUES	(
					@SettingsID,
					@SectionID,
					@RoleID,
					@AllowMask,
					@DenyMask
				)


		if not exists( select * from cs_ProductPermissions where SettingsID = @SettingsID and RoleID = @RoleID and ApplicationType = @ApplicationType)
			insert into cs_ProductPermissions ( SettingsID, RoleID, AllowMask, DenyMask, ApplicationType )
				values( @SettingsID, @RoleID, 0x0, 0x0, @ApplicationType )
				
		--reindex the posts
		exec cs_Posts_ReindexBySection @SectionID, @SettingsID
	end
	else
	begin
		insert into cs_ProductPermissions ( SettingsID, RoleID, AllowMask, DenyMask, ApplicationType )
			values( @SettingsID, @RoleID, @AllowMask, @DenyMask, @ApplicationType )
	end
END
-- UPDATE
ELSE IF @Action = 1
BEGIN
	
	if( @SectionID <> -1 ) 
	begin
		IF NOT EXISTS (SELECT SectionID FROM cs_SectionPermissions WHERE SectionID = @SectionID AND RoleID = @RoleID and SettingsID = @SettingsID )
			exec cs_Section_Permission_CreateUpdateDelete @SettingsID, @SectionID, @RoleID, 0, @AllowMask, @DenyMask, @ApplicationType
		ELSE
			UPDATE
				cs_SectionPermissions 
			SET
				AllowMask	= @AllowMask,
				DenyMask	= @DenyMask
			WHERE
				SectionID = @SectionID AND
				RoleID = @RoleID and SettingsID = @SettingsID

		if not exists( select * from cs_ProductPermissions where SettingsID = @SettingsID and RoleID = @RoleID and ApplicationType = @ApplicationType)
			insert into cs_ProductPermissions ( SettingsID, RoleID, AllowMask, DenyMask, ApplicationType )
				values( @SettingsID, @RoleID, 0x0, 0x0, @ApplicationType )
	end
	else
	begin
		if not exists( select * from cs_ProductPermissions where RoleID = @RoleID and SettingsID = @SettingsID and ApplicationType = @ApplicationType )
			exec cs_Section_Permission_CreateUpdateDelete @SettingsID, @SectionID, @RoleID, 0, @AllowMask, @DenyMask, @ApplicationType
		else
			UPDATE
				cs_ProductPermissions 
			SET
				AllowMask	= @AllowMask,
				DenyMask	= @DenyMask
			WHERE
				RoleID = @RoleID and SettingsID = @SettingsID and ApplicationType = @ApplicationType
	end

	-- Update users subscriptions
	IF @SectionID <> -1 
		EXEC cs_system_UpdateSubscriptions @RoleID, @SectionID, @SettingsID
END
ELSE IF @Action = 2
BEGIN
	if( @SectionID <> -1 )
		DELETE cs_SectionPermissions WHERE SectionID = @SectionID AND RoleID = @RoleID and SettingsID = @SettingsID
	else
	begin
		DELETE cs_SectionPermissions where RoleID = @RoleID and SettingsID = @SettingsID
		DELETE cs_ProductPermissions WHERE RoleID = @RoleID and SettingsID = @SettingsID and ApplicationType = @ApplicationType
	end
	
	-- Update users subscriptions
	IF @SectionID <> -1 
		EXEC cs_system_UpdateSubscriptions @RoleID, @SectionID, @SettingsID
END

END


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT EXECUTE ON [dbo].[cs_Section_Permission_CreateUpdateDelete] TO PUBLIC
GO
/***********************************************
* Sproc: cs_Section_RssPingback_Update
* File Date: 11/29/2006 10:07:31 AM
***********************************************/
Print 'Creating...cs_Section_RssPingback_Update'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Section_RssPingback_Update]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Section_RssPingback_Update]
GO






create procedure [dbo].cs_Section_RssPingback_Update (
	@SectionID int,
	@Pingback nvarchar(512),
	@Count int,
	@SettingsID int
)
AS
SET Transaction Isolation Level Read UNCOMMITTED
BEGIN

	IF EXISTS (SELECT SectionID FROM cs_ForumPingback WHERE SectionID = @SectionID AND Pingback = @Pingback)
		UPDATE
			cs_ForumPingback
		SET
			[Count] = [Count] + @Count,
			LastUpdated = GetDate()
		WHERE
			SectionID = @SectionID AND
			Pingback = @Pingback and SettingsID = @SettingsID
	ELSE
		INSERT INTO
			cs_ForumPingback
		VALUES
			(@SectionID, @Pingback, @Count, GetDate(), @SettingsID)
			

END







GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_Section_RssPingback_Update] to public
go
/***********************************************
* Sproc: cs_Section_UpdateSortOrder
* File Date: 11/29/2006 10:07:33 AM
***********************************************/
Print 'Creating...cs_Section_UpdateSortOrder'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Section_UpdateSortOrder]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Section_UpdateSortOrder]
GO
/***********************************************
* Sproc: cs_security_ValidateUserPasswordAnswer
* File Date: 11/29/2006 10:07:32 AM
***********************************************/
Print 'Creating...cs_security_ValidateUserPasswordAnswer'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_security_ValidateUserPasswordAnswer]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_security_ValidateUserPasswordAnswer]
GO



CREATE PROCEDURE [dbo].cs_security_ValidateUserPasswordAnswer
(
	@UserID int,
	@PasswordAnswer nvarchar(256)
)
AS
BEGIN
	SELECT 
		COUNT(cs_Users.UserID) 
	FROM 
		aspnet_membership, cs_Users
	WHERE
		aspnet_membership.UserID = cs_Users.MembershipID and cs_Users.UserID = @UserID
		AND (PasswordAnswer = @PasswordAnswer OR PasswordAnswer = NULL)
END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_security_ValidateUserPasswordAnswer] to public
go
/***********************************************
* Sproc: cs_Services_Get
* File Date: 11/29/2006 10:07:31 AM
***********************************************/
Print 'Creating...cs_Services_Get'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Services_Get]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Services_Get]
GO







create proc [dbo].cs_Services_Get
(
	@ServiceID int = 0,
	@SettingsID int
)
as 
SET Transaction Isolation Level Read UNCOMMITTED
	SELECT
		*
	FROM
		cs_Services
	WHERE
		ServiceID = @ServiceID or
		(@ServiceID = 0 and 1=1) and SettingsID = @SettingsID








GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_Services_Get] to public
go
/***********************************************
* Sproc: cs_Service_CreateUpdateDelete
* File Date: 11/29/2006 10:07:31 AM
***********************************************/
Print 'Creating...cs_Service_CreateUpdateDelete'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Service_CreateUpdateDelete]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Service_CreateUpdateDelete]
GO








create proc [dbo].cs_Service_CreateUpdateDelete
(
	  @ServiceID				int out
	, @DeleteService			bit = 0
	, @ServiceName				nvarchar(60)
	, @ServiceTypeCode			int
	, @ServiceAssemblyPath		nvarchar(512)
	, @ServiceFullClassName		nvarchar(512)
	, @ServiceWorkingDirectory	nvarchar(512)
	, @SettingsID int
)
AS
SET Transaction Isolation Level Read UNCOMMITTED
-- are we deleting the service
IF ( @DeleteService > 0 )
BEGIN

	DELETE cs_Services
	WHERE
		ServiceID	= @ServiceID and SettingsID = @SettingsID

	RETURN
END

IF( @ServiceID > 0 )
BEGIN

	UPDATE cs_Services SET
		  ServiceName				= @ServiceName
		, ServiceTypeCode			= @ServiceTypeCode
		, ServiceAssemblyPath		= @ServiceAssemblyPath
		, ServiceFullClassName		= @ServiceFullClassName
		, ServiceWorkingDirectory	= @ServiceWorkingDirectory
	WHERE
		ServiceID	= @ServiceID and SettingsID = @SettingsID

END
ELSE
BEGIN

	INSERT INTO cs_Services (
		ServiceName, ServiceTypeCode, ServiceAssemblyPath, ServiceFullClassName, ServiceWorkingDirectory, SettingsID
	) VALUES (
		@ServiceName, @ServiceTypeCode, @ServiceAssemblyPath, @ServiceFullClassName, @ServiceWorkingDirectory, @SettingsID
	)

	SET @ServiceID = @@identity

END

RETURN







GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_Service_CreateUpdateDelete] to public
go
/***********************************************
* Sproc: cs_SetForumSubscriptionType
* File Date: 11/29/2006 10:07:30 AM
***********************************************/
Print 'Creating...cs_SetForumSubscriptionType'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_SetForumSubscriptionType]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_SetForumSubscriptionType]
GO


if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_SetSectionSubscriptionType]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_SetSectionSubscriptionType]
GO





CREATE procedure [dbo].cs_SetSectionSubscriptionType
(
	@UserID int,
	@SectionID int,
	@subType int,
	@SettingsID int
)
 AS
SET Transaction Isolation Level Read UNCOMMITTED
if (@subType=0)
	DELETE from cs_TrackedSections where UserID=@UserID and SectionID=@SectionID and SettingsID = @SettingsID
ELSE
IF Exists (select SubscriptionType from cs_TrackedSections (nolock) where UserID=@UserID AND SectionID=@SectionID and SettingsID = @SettingsID)
	UPDATE cs_TrackedSections Set SubscriptionType=@subType where UserID=@UserID and SectionID=@SectionID and SettingsID = @SettingsID
ELSE
	INSERT INTO cs_TrackedSections (UserID, SectionID, SubscriptionType, SettingsID) values (@UserID, @SectionID, @subType, @SettingsID)







GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].cs_SetSectionSubscriptionType to public
go
/***********************************************
* Sproc: cs_SettingsIDs_Get
* File Date: 11/29/2006 10:07:31 AM
***********************************************/
Print 'Creating...cs_SettingsIDs_Get'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_SettingsIDs_Get]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_SettingsIDs_Get]
GO


CREATE  PROCEDURE [dbo].cs_SettingsIDs_Get
AS
SET Transaction Isolation Level Read UNCOMMITTED

Select 
	sm.SettingsID, 
	s.SiteUrl 
FROM 
	cs_SiteMappings sm,
	cs_Sites s
Where
	s.SiteID = sm.SiteID


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].cs_SettingsIDs_Get to public
go
/***********************************************
* Sproc: cs_shared_Threads_GetThreadSet
* File Date: 11/29/2006 10:07:32 AM
***********************************************/
Print 'Creating...cs_shared_Threads_GetThreadSet'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_shared_Threads_GetThreadSet]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_shared_Threads_GetThreadSet]
GO

CREATE  PROCEDURE [dbo].[cs_shared_Threads_GetThreadSet]
(
	@SectionID int,
	@PageIndex int, 
	@PageSize int,
	@sqlPopulate ntext,
	@UserID int,
	@IncludeCategories bit,
	@IncludePageIndex bit,
	@SettingsID int,
	@TotalRecords int output
)
AS
SET Transaction Isolation Level Read UNCOMMITTED

DECLARE @PageLowerBound int
DECLARE @PageUpperBound int
DECLARE @RowsToReturn int
DECLARE @TotalThreads int

-- First set the rowcount
SET @RowsToReturn = @PageSize * (@PageIndex + 1)


-- Set the page bounds
SET @PageLowerBound = @PageSize * @PageIndex
SET @PageUpperBound = @PageLowerBound + @PageSize + 1



-- Create a temp table to store the select results
CREATE TABLE #PageIndex 
(
	IndexID int IDENTITY (1, 1) NOT NULL,
	PostID int
)
 

--CREATE INDEX page_index ON #PageIndex(IndexID)

INSERT INTO #PageIndex (PostID)
EXEC (@sqlPopulate)

SET @TotalRecords = @@rowcount

SET ROWCOUNT @RowsToReturn

SELECT 
	SortOrder = jPI.IndexID,
	jP.PostID, 
	jP.ThreadID, 
	jP.ParentID, 
	jP.PostAuthor, 
	jP.UserID, 
	jP.SectionID, 
	jP.PostLevel, 
	jP.SortOrder, 
	jP.Subject, 
	jP.PostDate, 
	jP.IsApproved,
	jP.IsLocked as IsLocked,
	jP.IsIndexed, 
	jP.TotalViews as PostTotalViews,  --Conflicts with the Threads table which has precidence
	jP.Body, 
	jP.FormattedBody, 
	jP.IPAddress, 
	jP.PostType, 
	jP.PostMedia, 
	jP.EmoticonID, 
	jP.SettingsID, 
	jP.AggViews,
	jP.PostPropertyNames, 
	jP.PostPropertyValues,
	jP.PostConfiguration,
	jP.Points AS PostPoints,
	jp.AttachmentFilename,jp.ContentType, jp.IsRemote, jp.FriendlyFileName, jp.ContentSize, jp.[FileName],jp.Created, jP.Height, jP.Width,
	jP.PostName, 
	jP.ApplicationPostType, 
	jP.UserTime, 
	HasRead = 1,
	EditNotes = null, --(SELECT EditNotes FROM cs_PostEditNotes WHERE PostID = P.PostID),

	jT.PostAuthor as UserName,
	jT.TotalReplies as Replies, -- (SELECT COUNT(P2.PostID) FROM cs_Posts P2 (nolock) WHERE P2.ParentID = jP.PostID AND P2.PostLevel != 1)

        jT.UserID as ThreadUserID,
        jT.PostAuthor as ThreadPostAuthor,
        jT.PostDate as ThreadPostDate,
        jT.ThreadDate,
        jT.LastViewedDate,
        jT.StickyDate,
        jT.TotalViews as TotalViews,
        jT.TotalReplies,
        jT.MostRecentPostAuthorID,
        jT.MostRecentPostAuthor,
        jT.MostRecentPostID,
        jT.IsLocked as ThreadIsLocked,
        jT.IsSticky,
        jT.IsApproved as ThreadIsApproved,
        jT.RatingSum,
        jT.TotalRatings,
        jT.ThreadEmoticonID,
        jT.ThreadStatus,
        jT.SettingsID
	, jP.PostStatus, jP.SpamScore
FROM 
	#PageIndex jPI
	JOIN cs_vw_PostsWithAttachmentDetails jP ON jPI.PostID = jP.PostID
	JOIN cs_Threads jT ON jP.ThreadID = jT.ThreadID
WHERE 
	jPI.IndexID > @PageLowerBound
	AND jPI.IndexID < @PageUpperBound
	--AND jP.PostLevel = 1 	-- PostLevel=1 should mean it's a top-level thread starter,
	--AND jp.SettingsID = @SettingsID AND jT.SettingsID = @SettingsID
ORDER BY
	jPI.IndexID	-- this is the ordering system we're using populated from the @sqlPopulate


SET ROWCOUNT 0

IF @IncludeCategories = 1
BEGIN

	SELECT 
		Cats.[Name], jPI.PostID
	FROM 
		#PageIndex jPI
		JOIN cs_Posts_InCategories PIC ON jPI.PostID = PIC.PostID
		JOIN cs_Post_Categories Cats ON PIC.CategoryID = Cats.CategoryID
	WHERE 
		jPI.IndexID > @PageLowerBound
		AND jPI.IndexID < @PageUpperBound

End

If @IncludePageIndex = 1
BEGIN
	SELECT IndexID, PostID from #PageIndex ORDER BY IndexID
END

DROP TABLE #PageIndex

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_shared_Threads_GetThreadSet] to public
go
/***********************************************
* Sproc: cs_SiteSettings_Get
* File Date: 11/29/2006 10:07:31 AM
***********************************************/
Print 'Creating...cs_SiteSettings_Get'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_SiteSettings_Get]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_SiteSettings_Get]
GO


CREATE  PROCEDURE [dbo].cs_SiteSettings_Get
(
	@SiteUrl nvarchar(512) = null,
	@SettingsID int = 0,
	@ReturnAll bit
)
AS
SET Transaction Isolation Level Read UNCOMMITTED

If @ReturnAll = 0
Begin
Select 
		top 1 ss.SettingsXML, ss.Disabled, ss.Version, ss.SettingsKey, ss.ApplicationName, ss.SettingsID, s.SiteUrl 
		FROM 
			cs_SiteSettings ss
		LEFT OUTER JOIN 
			cs_SiteMappings sm ON ss.SettingsID = sm.SettingsID
		LEFT OUTER JOIN 
			cs_Sites s ON s.SiteID = sm.SiteID
		ORDER BY ss.SettingsID asc

End

ELSE IF @SiteUrl is null
Begin
Select 
		ss.SettingsXML, ss.Disabled, ss.Version, ss.SettingsKey, ss.ApplicationName, ss.SettingsID, s.SiteUrl 
		FROM 
			cs_SiteSettings ss
		LEFT OUTER JOIN 
			cs_SiteMappings sm ON ss.SettingsID = sm.SettingsID
		LEFT OUTER JOIN 
			cs_Sites s ON s.SiteID = sm.SiteID
		Where
			ss.SettingsID = @SettingsID
End
Else
Begin
	IF @SiteUrl = '*'
		Select 
			ss.SettingsXML, ss.Disabled, ss.Version, 
			ss.SettingsKey, ss.ApplicationName, ss.SettingsID, s.SiteUrl 
		FROM 
			cs_SiteSettings ss 
		JOIN 
			cs_SiteMappings sm ON ss.SettingsID = sm.SettingsID
		JOIN 
			cs_Sites s ON s.SiteID = sm.SiteID
	
	ELSE IF NOT EXISTS (SELECT * FROM cs_Sites WHERE SiteUrl = @SiteUrl OR SiteUrl = @SiteUrl + '/')
		RETURN
	ELSE
		Select 
			ss.SettingsXML, ss.Disabled, ss.Version, 
			ss.SettingsKey, ss.ApplicationName, ss.SettingsID, s.SiteUrl 
		FROM 
			cs_SiteSettings ss 
		JOIN 
			cs_SiteMappings sm ON ss.SettingsID = sm.SettingsID
		JOIN 
			cs_Sites s ON s.SiteID = sm.SiteID
		Where
			(s.SiteUrl = @SiteUrl OR s.SiteUrl = @SiteUrl + '/')
End

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].cs_SiteSettings_Get to public
go
/***********************************************
* Sproc: cs_SiteSettings_Save
* File Date: 11/29/2006 10:07:33 AM
***********************************************/
Print 'Creating...cs_SiteSettings_Save'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_SiteSettings_Save]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_SiteSettings_Save]
GO
--Select * FROM cs_SiteSettings

CREATE procedure [dbo].cs_SiteSettings_Save
(
	@Disabled		smallint,
	@SettingsXML	 	ntext = null,
	@ApplicationName	nvarchar(256),
	@SettingsID 		int
)
AS
SET Transaction Isolation Level Read UNCOMMITTED
BEGIN
		UPDATE
			cs_SiteSettings
		SET
			Disabled = @Disabled,
			SettingsXML = @SettingsXML,
			ApplicationName = @ApplicationName
		WHERE
			SettingsID  = @SettingsID
END













GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_SiteSettings_Save] to public
go
/***********************************************
* Sproc: cs_Site_GetSiteUrls
* File Date: 11/29/2006 10:07:33 AM
***********************************************/
Print 'Creating...cs_Site_GetSiteUrls'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Site_GetSiteUrls]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Site_GetSiteUrls]
GO

CREATE    procedure [dbo].cs_Site_GetSiteUrls
AS

select
 lower(SS.ApplicationName) as ApplicationName, S.SiteUrl
from cs_SiteSettings SS
left join cs_SiteMappings SM on (SM.SettingsID = SS.SettingsID)
left join cs_Sites S on (S.SiteID = SM.SiteID)

GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].cs_Site_GetSiteUrls to public
go
/***********************************************
* Sproc: cs_Site_Statistics
* File Date: 11/29/2006 10:07:30 AM
***********************************************/
Print 'Creating...cs_Site_Statistics'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Site_Statistics]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Site_Statistics]
GO




CREATE PROCEDURE [dbo].cs_Site_Statistics
(
	@SettingsID int
)
AS

SET Transaction Isolation Level Read UNCOMMITTED

-- Do we need to update the statistics?
DECLARE @LastUpdate datetime
DECLARE @ApplicationId uniqueidentifier
DECLARE @ModeratorRoleID AS uniqueidentifier

SET @ApplicationId = (SELECT ApplicationId FROM aspnet_Applications A, cs_SiteSettings S WHERE A.ApplicationName = S.ApplicationName AND SettingsID = @SettingsID)
SET @ModeratorRoleID = (SELECT RoleId from aspnet_Roles WHERE LoweredRoleName = 'moderator' AND ApplicationId = @ApplicationId)
SET @LastUpdate = ISNULL((SELECT MAX(DateCreated) FROM cs_statistics_Site where SettingsID = @SettingsID), '1/1/1797')



-- SELECT current statistics
SELECT 
	S.*,
	CurrentAnonymousUsers = (SELECT Count(*) FROM cs_AnonymousUsers where SettingsID = @SettingsID),
	MostReadSubject = isnull((SELECT Subject FROM cs_Posts, cs_Sections WHERE PostID = S.MostReadPostID and cs_Posts.SettingsID = @SettingsID and cs_Posts.SectionID = cs_Sections.SectionID and cs_Sections.ApplicationType = 0),''),
	MostViewsSubject = isnull((SELECT Subject FROM cs_Posts, cs_Sections WHERE PostID = S.MostViewsPostID and cs_Posts.SettingsID = @SettingsID and cs_Posts.SectionID = cs_Sections.SectionID and cs_Sections.ApplicationType = 0),''),
	MostActiveSubject = isnull((SELECT Subject FROM cs_Posts, cs_Sections WHERE PostID = S.MostActivePostID and cs_Posts.SettingsID = @SettingsID and cs_Posts.SectionID = cs_Sections.SectionID and cs_Sections.ApplicationType = 0),''),
	MostActiveUser = isnull((SELECT UserName FROM cs_vw_Users_FullUser WHERE cs_UserID = S.MostActiveUserID and SettingsID = @SettingsID),''),
	NewestUser = isnull((SELECT UserName FROM cs_vw_Users_FullUser WHERE cs_UserID = S.NewestUserID and SettingsID = @SettingsID),'')
FROM
	cs_statistics_Site S
WHERE
	DateCreated = @LastUpdate  and SettingsID = @SettingsID

-- SELECT TOP 100 Users
SELECT TOP 100
	S.TotalPosts,
	U.*
FROM
	cs_statistics_User S,
	cs_vw_Users_FullUser U
WHERE
	S.UserID = U.cs_UserID AND
	U.EnableDisplayInMemberList = 1 AND
	U.cs_UserID > 0 and U.SettingsID = @SettingsID and S.SettingsID = @SettingsID
ORDER BY
	S.TotalPosts DESC

-- SELECT top 10 Moderators
SELECT TOP 10
	U.*,
	M.PostsModerated
FROM
	cs_vw_Users_FullUser U,
	aspnet_UsersInRoles R,
	cs_Moderators M
WHERE
	U.UserId = R.UserId AND
	R.RoleId = @ModeratorRoleID AND
	U.cs_UserID = M.UserID AND
	M.PostsModerated > 0 AND 
	U.SettingsID = @SettingsID AND 
	M.SettingsID = @SettingsID
ORDER BY
	PostsModerated DESC

-- SELECT Moderator actions
SELECT
	Description,
	TotalActions
FROM
	cs_ModerationAction
WHERE
	TotalActions > 0
ORDER BY
	TotalActions DESC 



GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_Site_Statistics] to public
go
/***********************************************
* Sproc: cs_Smiley_CreateUpdateDelete
* File Date: 11/29/2006 10:07:32 AM
***********************************************/
Print 'Creating...cs_Smiley_CreateUpdateDelete'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Smiley_CreateUpdateDelete]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Smiley_CreateUpdateDelete]
GO



CREATE proc [dbo].cs_Smiley_CreateUpdateDelete
(
	  @SmileyID		int out
	, @DeleteSmiley	bit = 0
	, @SmileyCode	nvarchar(20)
	, @SmileyUrl	nvarchar(512)
	, @SmileyText	nvarchar(512)
	, @BracketSafe	bit = 0
	, @SettingsID int
)
as
SET Transaction Isolation Level Read UNCOMMITTED

IF( @DeleteSmiley > 0 ) 
BEGIN

	DELETE cs_Smilies
	WHERE
		SmileyID = @SmileyID and SettingsID = @SettingsID

	RETURN
END

IF( @SmileyID > 0 ) 
BEGIN
	UPDATE cs_Smilies SET
		  SmileyCode	= @SmileyCode
		, SmileyUrl		= @SmileyUrl
		, SmileyText	= @SmileyText
		, BracketSafe	= @BracketSafe
	WHERE
		SmileyID	= @SmileyID and SettingsID = @SettingsID
END
ELSE
BEGIN

	INSERT INTO cs_Smilies (
		SmileyCode, SmileyUrl, SmileyText, BracketSafe, SettingsID
	) VALUES (
		@SmileyCode, @SmileyUrl, @SmileyText, @BracketSafe, @SettingsID
	)

	SET @SmileyID = @@identity
END
RETURN









GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_Smiley_CreateUpdateDelete] to public
go
/***********************************************
* Sproc: cs_Smilies_Get
* File Date: 11/29/2006 10:07:30 AM
***********************************************/
Print 'Creating...cs_Smilies_Get'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Smilies_Get]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Smilies_Get]
GO







create proc [dbo].cs_Smilies_Get
(
	@SettingsID int
)
as
SET Transaction Isolation Level Read UNCOMMITTED
	select
		*
	from
		cs_Smilies
	WHERE
		SettingsID = @SettingsID






GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_Smilies_Get] to public
go
/***********************************************
* Sproc: cs_Styles_Get
* File Date: 11/29/2006 10:07:30 AM
***********************************************/
Print 'Creating...cs_Styles_Get'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Styles_Get]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Styles_Get]
GO








create proc [dbo].cs_Styles_Get
(
	@StyleID	int = 0,
	@SettingsID int
)
as
SET Transaction Isolation Level Read UNCOMMITTED
	select
		*
	from
		cs_Styles
	WHERE
		StyleID = @StyleID OR
		(
			@StyleID = 0 AND
			1=1
		) and SettingsID = @SettingsID







GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_Styles_Get] to public
go
/***********************************************
* Sproc: cs_Style_CreateUpdateDelete
* File Date: 11/29/2006 10:07:30 AM
***********************************************/
Print 'Creating...cs_Style_CreateUpdateDelete'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Style_CreateUpdateDelete]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Style_CreateUpdateDelete]
GO







create proc [dbo].cs_Style_CreateUpdateDelete
(
	  @StyleID				int out
	, @DeleteStyle			bit = 0
	, @StyleName			varchar(30)
	, @StyleSheetTemplate	varchar(30)
	, @BodyBackgroundColor	int
	, @BodyTextColor		int
	, @LinkVisited			int
	, @LinkHover			int
	, @LinkActive			int
	, @RowColorPrimary		int
	, @RowColorSecondary	int
	, @RowColorTertiary		int
	, @RowClassPrimary		varchar(30)
	, @RowClassSecondary	varchar(30)
	, @RowClassTertiary		varchar(30)
	, @HeaderColorPrimary	int
	, @HeaderColorSecondary	int
	, @HeaderColorTertiary	int
	, @HeaderStylePrimary	varchar(30)
	, @HeaderStyleSecondary	varchar(30)
	, @HeaderStyleTertiary	varchar(30)
	, @CellColorPrimary		int
	, @CellColorSecondary	int
	, @CellColorTertiary	int
	, @CellClassPrimary		varchar(30)
	, @CellClassSecondary	varchar(30)
	, @CellClassTertiary	varchar(30)
	, @FontFacePrimary		varchar(30)	
	, @FontFaceSecondary	varchar(30)
	, @FontFaceTertiary		varchar(30)
	, @FontSizePrimary		smallint
	, @FontSizeSecondary	smallint
	, @FontSizeTertiary		smallint
	, @FontColorPrimary		int
	, @FontColorSecondary	int
	, @FontColorTertiary	int
	, @SpanClassPrimary		varchar(30)
	, @SpanClassSecondary	varchar(30)
	, @SpanClassTertiary	varchar(30)
	, @SettingsID int
)
AS
SET Transaction Isolation Level Read UNCOMMITTED
IF( @DeleteStyle = 1 ) 
BEGIN
	
	DELETE cs_Styles
	WHERE
		StyleID	= @StyleID and SettingsID = @SettingsID

	RETURN
END

IF( @StyleID > 0 )
BEGIN

	UPDATE cs_Styles SET
		  StyleName 			= @StyleName
		, StyleSheetTemplate 	= @StyleSheetTemplate
		, BodyBackgroundColor 	= @BodyBackgroundColor
		, BodyTextColor 		= @BodyTextColor
		, LinkVisited 			= @LinkVisited
		, LinkHover 			= @LinkHover
		, LinkActive 			= @LinkActive
		, RowColorPrimary 		= @RowColorPrimary
		, RowColorSecondary 	= @RowColorSecondary
		, RowColorTertiary 		= @RowColorTertiary
		, RowClassPrimary 		= @RowClassPrimary
		, RowClassSecondary 	= @RowClassSecondary
		, RowClassTertiary 		= @RowClassTertiary
		, HeaderColorPrimary 	= @HeaderColorPrimary
		, HeaderColorSecondary	= @HeaderColorSecondary
		, HeaderColorTertiary 	= @HeaderColorTertiary
		, HeaderStylePrimary 	= @HeaderStylePrimary
		, HeaderStyleSecondary 	= @HeaderStyleSecondary
		, HeaderStyleTertiary 	= @HeaderStyleTertiary
		, CellColorPrimary 		= @CellColorPrimary
		, CellColorSecondary	= @CellColorSecondary
		, CellColorTertiary 	= @CellColorTertiary
		, CellClassPrimary 		= @CellClassPrimary
		, CellClassSecondary 	= @CellClassSecondary
		, CellClassTertiary 	= @CellClassTertiary
		, FontFacePrimary 		= @FontFacePrimary
		, FontFaceSecondary 	= @FontFaceSecondary
		, FontFaceTertiary 		= @FontFaceTertiary
		, FontSizePrimary 		= @FontSizePrimary
		, FontSizeSecondary 	= @FontSizeSecondary
		, FontSizeTertiary 		= @FontSizeTertiary
		, FontColorPrimary 		= @FontColorPrimary
		, FontColorSecondary 	= @FontColorSecondary
		, FontColorTertiary 	= @FontColorTertiary
		, SpanClassPrimary 		= @SpanClassPrimary
		, SpanClassSecondary 	= @SpanClassSecondary
		, SpanClassTertiary 	= @SpanClassTertiary
	WHERE
		StyleID = @StyleID and SettingsID = @SettingsID


END
ELSE
BEGIN

	INSERT INTO cs_Styles (
		  StyleName				, StyleSheetTemplate		, BodyBackgroundColor		, BodyTextColor
		, LinkVisited			, LinkHover					, LinkActive				, RowColorPrimary
		, RowColorSecondary		, RowColorTertiary			, RowClassPrimary			, RowClassSecondary
		, RowClassTertiary		, HeaderColorPrimary		, HeaderColorSecondary		, HeaderColorTertiary
		, HeaderStylePrimary	, HeaderStyleSecondary		, HeaderStyleTertiary		, CellColorPrimary
		, CellColorSecondary	, CellColorTertiary			, CellClassPrimary			, CellClassSecondary
		, CellClassTertiary		, FontFacePrimary			, FontFaceSecondary			, FontFaceTertiary
		, FontSizePrimary		, FontSizeSecondary			, FontSizeTertiary			, FontColorPrimary
		, FontColorSecondary	, FontColorTertiary			, SpanClassPrimary			, SpanClassSecondary
		, SpanClassTertiary, SettingsID
	) VALUES (
		  @StyleName			, @StyleSheetTemplate		, @BodyBackgroundColor		, @BodyTextColor		, @LinkVisited			, @LinkHover				, @LinkActive				, @RowColorPrimary
		, @RowColorSecondary	, @RowColorTertiary			, @RowClassPrimary			, @RowClassSecondary
		, @RowClassTertiary		, @HeaderColorPrimary		, @HeaderColorSecondary		, @HeaderColorTertiary
		, @HeaderStylePrimary	, @HeaderStyleSecondary		, @HeaderStyleTertiary		, @CellColorPrimary
		, @CellColorSecondary	, @CellColorTertiary		, @CellClassPrimary			, @CellClassSecondary
		, @CellClassTertiary	, @FontFacePrimary			, @FontFaceSecondary		, @FontFaceTertiary
		, @FontSizePrimary		, @FontSizeSecondary		, @FontSizeTertiary			, @FontColorPrimary
		, @FontColorSecondary	, @FontColorTertiary		, @SpanClassPrimary			, @SpanClassSecondary
		, @SpanClassTertiary, @SettingsID
	)

	SELECT @StyleID = @@IDENTITY
END
RETURN







GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_Style_CreateUpdateDelete] to public
go
/***********************************************
* Sproc: cs_System_AddNewUrl.sql
* File Date: 11/29/2006 10:07:34 AM
***********************************************/
Print 'Creating...cs_System_AddNewUrl.sql'



if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_System_AddNewUrl]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_System_AddNewUrl]
GO


/***************************************************
Adds another Url to an existing SiteSettings Record

Author: Scott Watermasysk
Date: 10/21/2004
****************************************************/

CREATE Proc [dbo].cs_System_AddNewUrl
(
	@ExistingUrl nvarchar(512),
	@NewUrl nvarchar(512)
)

as

if exists(Select SiteID FROM cs_Sites where SiteUrl = @NewUrl)
Return -1 -->> The site @NewUrl already exists

Declare @SiteID int
Declare @SettingsID int 
Declare @NewSiteID int

Select @SiteID = SiteID FROM cs_Sites where SiteUrl = @ExistingUrl

If @SiteID is null
Return -2 -->> The site at @ExistingUrl does not Exist

Select @SettingsID = SettingsID FROM cs_SiteMappings where SiteID = @SiteID
If @SettingsID is null
Return -3 -->> This Application is not yet mapped

Insert cs_Sites Values (@NewUrl)
Select @NewSiteID = @@Identity

if @NewSiteID is null
Return -4 -->> Insert of new site failed

Insert cs_SiteMappings Values (@SettingsID, @NewSiteID)
Return 1

GO

grant execute on [dbo].[cs_System_AddNewUrl] to public
go
/***********************************************
* Sproc: cs_system_CleanForumsRead
* File Date: 11/29/2006 10:07:31 AM
***********************************************/
Print 'Creating...cs_system_CleanForumsRead'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_system_CleanForumsRead]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_system_CleanForumsRead]
GO





create   procedure [dbo].cs_system_CleanForumsRead
(
	@SectionID int,
	@SettingsID int
)
AS
SET Transaction Isolation Level Read UNCOMMITTED
BEGIN
	DELETE
		cs_SectionsRead
	WHERE
		SectionID = @SectionID and SettingsID = @SettingsID
END




GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_system_CleanForumsRead] to public
go
/***********************************************
* Sproc: cs_system_CreateAlias
* File Date: 11/29/2006 10:07:32 AM
***********************************************/
Print 'Creating...cs_system_CreateAlias'

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_system_CreateAlias]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_system_CreateAlias]
GO

--exec cs_system_CreateAlias 'localhost/blahx','dev'


/***********************************************
* Sproc: cs_system_CreateCommunity
* File Date: 11/29/2006 10:07:30 AM
***********************************************/
Print 'Creating...cs_system_CreateCommunity'

--restore database CommunityServer from disk='c:\CommunityServer.bak'

go
if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_system_CreateCommunity]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_system_CreateCommunity]
GO

--exec cs_system_CreateCommunity 'localhost/cs55sdf2','devs55ssss', 'admin@example.com', 'admin', 'sTrongPassw0rd', 0, 1

create Proc [dbo].cs_system_CreateCommunity
(
	@SiteUrl nvarchar(512),
	@ApplicationName nvarchar(512),
	@AdminEmail nvarchar(256),
	@AdminUserName nvarchar(256),
	@AdminPassword nvarchar(256),
	@PasswordFormat int = 0,	-- 0 = clear text, 1 = encrypted
	@CreateSamples bit = 1
)

as

--We must have both these values to continue
if(@SiteUrl is null OR @ApplicationName is  null)
BEGIN
	Select -1
	RETURN
END

--@SiteUrl must be unique
if exists(Select SiteID FROM cs_Sites where Lower(SiteUrl) = Lower(@SiteUrl))
BEGIN
	Select -2
	RETURN
END

Declare @SettingsID int
DECLARE @SiteID int 
Declare @ApplicationID uniqueidentifier
Declare @AdminUserID uniqueidentifier
DECLARE @Version nvarchar(64)
DECLARE @IsApplicationCreated bit
DECLARE @GroupID int
DECLARE @AdminRoleID uniqueidentifier

Set @IsApplicationCreated = 0

Set @Version = null

--Insert Site Record. This maps a Url to an ID
Insert cs_Sites (SiteUrl) Values(@SiteUrl)
Select @SiteID = @@Identity

--Get or Create the Application ID.
--An ApplicationName/ID can exist in more than one site, so it does not need to be unique
Set @ApplicationID = null
Select @ApplicationID = ApplicationId FROM aspnet_Applications where  LoweredApplicationName = Lower(@ApplicationName)

if(@ApplicationID is  null)
BEGIN
	exec aspnet_Applications_CreateApplication @ApplicationName, @ApplicationId = @ApplicationID OUTPUT
	Set @IsApplicationCreated = 1
	Print 'Created New Application ' + @ApplicationName + '(' + Convert(varchar(36),@ApplicationID) + ')'

END
ELSE
BEGIN
	SET @IsApplicationCreated = 0
END

--Insert a record into the SiteSettings table
INSERT cs_SiteSettings (Disabled, Version, SettingsKey, ApplicationName)
VALUES (0,@Version,newID(),@ApplicationName)

--Get the SettingsID
Select @SettingsID = @@Identity
Print 'Created new SettingsID ' + Convert(varchar(5),@SettingsID)

--Site Mappings bind a specific Url to a SiteSetting (and ApplicationName/ID)
Insert cs_SiteMappings (SettingsID, SiteID) Values (@SettingsID, @SiteID)
Print 'SettingsID and ApplicationID Mapped'




print 'Creating moderation actions...'
INSERT INTO cs_ModerationAction (ModerationAction, [Description], TotalActions, SettingsID) VALUES (1, 'ApprovePost', 0, @SettingsID)
INSERT INTO cs_ModerationAction (ModerationAction, [Description], TotalActions, SettingsID) VALUES (2, 'EditPost', 0, @SettingsID)
INSERT INTO cs_ModerationAction (ModerationAction, [Description], TotalActions, SettingsID) VALUES (3, 'MovePost', 0, @SettingsID)
INSERT INTO cs_ModerationAction (ModerationAction, [Description], TotalActions, SettingsID) VALUES (4, 'DeletePost', 0, @SettingsID)
INSERT INTO cs_ModerationAction (ModerationAction, [Description], TotalActions, SettingsID) VALUES (5, 'LockPost', 0, @SettingsID)
INSERT INTO cs_ModerationAction (ModerationAction, [Description], TotalActions, SettingsID) VALUES (6, 'UnlockPost', 0, @SettingsID)
INSERT INTO cs_ModerationAction (ModerationAction, [Description], TotalActions, SettingsID) VALUES (7, 'MergePost', 0, @SettingsID)
INSERT INTO cs_ModerationAction (ModerationAction, [Description], TotalActions, SettingsID) VALUES (8, 'SplitPost', 0, @SettingsID)
INSERT INTO cs_ModerationAction (ModerationAction, [Description], TotalActions, SettingsID) VALUES (9, 'EditUser', 0, @SettingsID)
INSERT INTO cs_ModerationAction (ModerationAction, [Description], TotalActions, SettingsID) VALUES (10, 'UnmoderateUser', 0, @SettingsID)
INSERT INTO cs_ModerationAction (ModerationAction, [Description], TotalActions, SettingsID) VALUES (11, 'ModerateUser', 0, @SettingsID)
INSERT INTO cs_ModerationAction (ModerationAction, [Description], TotalActions, SettingsID) VALUES (12, 'BanUser', 0, @SettingsID)
INSERT INTO cs_ModerationAction (ModerationAction, [Description], TotalActions, SettingsID) VALUES (13, 'UnbanUser', 0, @SettingsID)
INSERT INTO cs_ModerationAction (ModerationAction, [Description], TotalActions, SettingsID) VALUES (14, 'ResetPassword', 0, @SettingsID)
INSERT INTO cs_ModerationAction (ModerationAction, [Description], TotalActions, SettingsID) VALUES (15, 'ChangePassword', 0, @SettingsID)
INSERT INTO cs_ModerationAction (ModerationAction, [Description], TotalActions, SettingsID) VALUES (16, 'PostIsAnnouncement', 0, @SettingsID)
INSERT INTO cs_ModerationAction (ModerationAction, [Description], TotalActions, SettingsID) VALUES (17, 'PostIsNotAnnoucement', 0, @SettingsID)
INSERT INTO cs_ModerationAction (ModerationAction, [Description], TotalActions, SettingsID) VALUES (18, 'UnApprovePost', 0, @SettingsID)
INSERT INTO cs_ModerationAction (ModerationAction, [Description], TotalActions, SettingsID) VALUES (19, 'DeleteSection', 0, @SettingsID)
INSERT INTO cs_ModerationAction (ModerationAction, [Description], TotalActions, SettingsID) VALUES (20, 'IgnoreUser', 0, @SettingsID)
INSERT INTO cs_ModerationAction (ModerationAction, [Description], TotalActions, SettingsID) VALUES (21, 'UnignoreUser', 0, @SettingsID)


/*=========================================================
WORD CENSORS (default list)
=========================================================*/
print 'Creating a default list of censored words...'
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'dyke', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'shit', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'amcik', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'arse', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'asshole', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'assramer', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'atouche', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'ayir', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'b17ch', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'b1tch', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'bastard', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'bi7ch', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'bitch', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'boiolas', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'bollock', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'breast', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'c0ck', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'cabron', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'cawk', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'cazzo', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'chink', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'chraa', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'chuj', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'cipa', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'clit', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'clits', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'cock', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'cum', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'cunt', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'd4mn', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'dago', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'daygo', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'dego', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'dick', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'dildo', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'dirsa', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'dupa', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'dziwka', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'ekrem', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'ekto', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'enculer', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'faen', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'fag', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'fancul', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'fatass', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'fcuk', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'feces', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'ficken', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'fitta', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'fitte', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'flikker', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'fotze', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'fuk', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'fuck', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'futkretzn', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'fux0r', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'guiena', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'h0r', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'h4x0r', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'helvete', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'hoer', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'honkey', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'Huevon', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'hui', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'injun', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'kawk', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'kike', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'ootzak', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'knulle', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'kraut', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'kuk', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'kuksuger', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'Kurac', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'kurwa', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'kusi', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'kyrp', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'lesbian', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'lesbo', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'mamhoon', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'masturbat', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'merd', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'merde', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'mibun', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'monkleigh', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'motherfucker', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'mouliewop', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'muie', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'mulkku', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'muschi', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'nazis', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'nepesaurio', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'nigga', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'nigger', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'nutsack', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'orospu', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'paska', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'pendejo', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'penisperse', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'phuck', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'picka', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'pierdol', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'pillu', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'pimmel', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'pimpis', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'pizdapoontsee', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'pr0n', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'preteen', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'preud', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'prick', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'pula', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'pule', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'pusse', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'pussy', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'puta', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'puto', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'qaHbeh', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'queef', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'queer', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'qweef', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'rautenbergschaffer', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'scheiss', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'scheisse', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'schlampe', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'schmuck', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'scrotum', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'sharmuta', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'sharmute', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'shemale', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'shipal', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'shiz', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'shiat', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'Skribz', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'skurwysyn', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'slut', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'smut', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'sphencter', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'spic', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'spierdalaj', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'splooge', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'suka', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'tits', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'twatty', '***')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'javascript\:', 'BLOCKED SCRIPT')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'jscript\:', 'BLOCKED SCRIPT')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'vbscript\:', 'BLOCKED SCRIPT')
INSERT INTO cs_Censorship (SettingsID, Word, Replacement) Values (@SettingsID, 'expression\(*.\)', 'BLOCKED EXPRESSION')

print 'Disallowed usernames...'
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*dyke*')
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*shit*')
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*amcik*')
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*arse*')
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*asshole*')
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*assramer*')
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*atouche*')
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*ayir*')
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*b17ch*')
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*b1tch*')
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*bastard*')
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*bi7ch*')
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*bitch*')
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*boiolas*')
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*bollock*')
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*breast*')
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*c0ck*')
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*cabron*')
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*cawk*')
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*cazzo*')
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*chink*')
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*chraa*')
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*chuj*')
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*cipa*')
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*clit*')
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*clits*')
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*cock*')
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*cum*')
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*cunt*')
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*d4mn*')
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*dago*')
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*daygo*')
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*dego*')
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*dick*')
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*dildo*')
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*dirsa*')
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*dupa*')
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*dziwka*')
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*ekrem*')
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*ekto*')
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*enculer*')
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*faen*')
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*fag*')
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*fancul*')
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*fatass*')
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*fcuk*')
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*feces*')
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*ficken*')
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*fitta*')
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*fitte*')
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*flikker*')
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*fotze*')
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*fuk*')
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*fuck*')
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*futkretzn*')
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*fux0r*')
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*guiena*')
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*h0r*')
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*h4x0r*')
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*helvete*')
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*hoer*')
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*honkey*')
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*Huevon*')
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*hui*')
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*injun*')
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*kawk*')
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*kike*')
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*ootzak*')
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*knulle*')
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*kraut*')
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*kuk*')
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*kuksuger*')
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*Kurac*')
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*kurwa*')INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*kusi*')
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*kyrp*')
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*lesbian*')
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*lesbo*')
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*mamhoon*')
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*masturbat*')
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*merd*')
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*merde*')
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*mibun*')
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*monkleigh*')
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*motherfucker*')
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*mouliewop*')
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*muie*')
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*mulkku*')
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*muschi*')
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*nazis*')
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*nepesaurio*')
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*nigga*')
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*nigger*')
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*nutsack*')
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*orospu*')
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*paska*')
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*pendejo*')
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*penisperse*')
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*phuck*')
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*picka*')
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*pierdol*')
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*pillu*')
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*pimmel*')
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*pimpis*')
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*pizdapoontsee*')
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*pr0n*')
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*preteen*')
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*preud*')
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*prick*')
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*pula*')
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*pule*')
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*pusse*')
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*pussy*')
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*puta*')
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*puto*')
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*qaHbeh*')
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*queef*')
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*queer*')
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*qweef*')
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*rautenbergschaffer*')
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*scheiss*')
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*scheisse*')
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*schlampe*')
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*schmuck*')
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*scrotum*')
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*sharmuta*')
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*sharmute*')
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*shemale*')
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*shipal*')
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*shiz*')
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*shiat*')
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*Skribz*')
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*skurwysyn*')
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*slut*')
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*smut*')
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*sphencter*')
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*spic*')
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*spierdalaj*')
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*splooge*')
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*suka*')
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*tits*')
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*twatty*')
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*satan*')
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*god*')
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*superuser*')
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*administrator*')
INSERT INTO cs_DisallowedNames (SettingsID, DisallowedName) Values (@SettingsID, '*admin*')

print 'Creating the default smilies...'
INSERT INTO cs_Smilies (SmileyCode, SmileyUrl, SmileyText, BracketSafe, SettingsID) VALUES (':)', 'emoticons/emotion-1.gif', 'Smile', 0, @SettingsID)
INSERT INTO cs_Smilies (SmileyCode, SmileyUrl, SmileyText, BracketSafe, SettingsID) VALUES (':D', 'emoticons/emotion-2.gif', 'Big Smile', 0, @SettingsID)
INSERT INTO cs_Smilies (SmileyCode, SmileyUrl, SmileyText, BracketSafe, SettingsID) VALUES (':O', 'emoticons/emotion-3.gif', 'Surprise', 0, @SettingsID)
INSERT INTO cs_Smilies (SmileyCode, SmileyUrl, SmileyText, BracketSafe, SettingsID) VALUES (':P', 'emoticons/emotion-4.gif', 'Stick out tongue', 0, @SettingsID)
INSERT INTO cs_Smilies (SmileyCode, SmileyUrl, SmileyText, BracketSafe, SettingsID) VALUES (';)', 'emoticons/emotion-5.gif', 'Wink', 0, @SettingsID)
INSERT INTO cs_Smilies (SmileyCode, SmileyUrl, SmileyText, BracketSafe, SettingsID) VALUES (':(', 'emoticons/emotion-6.gif', 'Sad', 0, @SettingsID)
INSERT INTO cs_Smilies (SmileyCode, SmileyUrl, SmileyText, BracketSafe, SettingsID) VALUES (':S', 'emoticons/emotion-7.gif', 'Tongue Tied', 0, @SettingsID)
INSERT INTO cs_Smilies (SmileyCode, SmileyUrl, SmileyText, BracketSafe, SettingsID) VALUES (':|', 'emoticons/emotion-8.gif', 'Indifferent', 0, @SettingsID)
INSERT INTO cs_Smilies (SmileyCode, SmileyUrl, SmileyText, BracketSafe, SettingsID) VALUES (':''(', 'emoticons/emotion-9.gif', 'Crying', 0, @SettingsID)
INSERT INTO cs_Smilies (SmileyCode, SmileyUrl, SmileyText, BracketSafe, SettingsID) VALUES (':$', 'emoticons/emotion-10.gif', 'Embarrassed', 0, @SettingsID)
INSERT INTO cs_Smilies (SmileyCode, SmileyUrl, SmileyText, BracketSafe, SettingsID) VALUES ('H', 'emoticons/emotion-11.gif', 'Cool', 0, @SettingsID)
INSERT INTO cs_Smilies (SmileyCode, SmileyUrl, SmileyText, BracketSafe, SettingsID) VALUES (':@', 'emoticons/emotion-12.gif', 'Angry', 0, @SettingsID)
INSERT INTO cs_Smilies (SmileyCode, SmileyUrl, SmileyText, BracketSafe, SettingsID) VALUES ('A', 'emoticons/emotion-13.gif', 'Angel', 0, @SettingsID)
INSERT INTO cs_Smilies (SmileyCode, SmileyUrl, SmileyText, BracketSafe, SettingsID) VALUES ('6', 'emoticons/emotion-14.gif', 'Devil', 0, @SettingsID)
INSERT INTO cs_Smilies (SmileyCode, SmileyUrl, SmileyText, BracketSafe, SettingsID) VALUES ('8-|', 'emoticons/emotion-15.gif', 'Geeked', 0, @SettingsID)
INSERT INTO cs_Smilies (SmileyCode, SmileyUrl, SmileyText, BracketSafe, SettingsID) VALUES (':#', 'emoticons/emotion-16.gif', 'Zip it!', 0, @SettingsID)
INSERT INTO cs_Smilies (SmileyCode, SmileyUrl, SmileyText, BracketSafe, SettingsID) VALUES (':-*', 'emoticons/emotion-17.gif', 'Whisper', 0, @SettingsID)
INSERT INTO cs_Smilies (SmileyCode, SmileyUrl, SmileyText, BracketSafe, SettingsID) VALUES (':^)', 'emoticons/emotion-18.gif', 'Huh?', 0, @SettingsID)
INSERT INTO cs_Smilies (SmileyCode, SmileyUrl, SmileyText, BracketSafe, SettingsID) VALUES ('<:o)', 'emoticons/emotion-19.gif', 'Party!!!', 0, @SettingsID)
INSERT INTO cs_Smilies (SmileyCode, SmileyUrl, SmileyText, BracketSafe, SettingsID) VALUES ('|-)', 'emoticons/emotion-20.gif', 'Sleep', 0, @SettingsID)
INSERT INTO cs_Smilies (SmileyCode, SmileyUrl, SmileyText, BracketSafe, SettingsID) VALUES ('Y', 'emoticons/emotion-21.gif', 'Yes', 0, @SettingsID)
INSERT INTO cs_Smilies (SmileyCode, SmileyUrl, SmileyText, BracketSafe, SettingsID) VALUES ('B', 'emoticons/emotion-22.gif', 'Beer', 0, @SettingsID)
INSERT INTO cs_Smilies (SmileyCode, SmileyUrl, SmileyText, BracketSafe, SettingsID) VALUES ('{', 'emoticons/emotion-24.gif', 'Left Hug', 0, @SettingsID)
INSERT INTO cs_Smilies (SmileyCode, SmileyUrl, SmileyText, BracketSafe, SettingsID) VALUES ('8', 'emoticons/emotion-29.gif', 'Music', 0, @SettingsID)
INSERT INTO cs_Smilies (SmileyCode, SmileyUrl, SmileyText, BracketSafe, SettingsID) VALUES ('*', 'emoticons/emotion-30.gif', 'Star', 0, @SettingsID)
INSERT INTO cs_Smilies (SmileyCode, SmileyUrl, SmileyText, BracketSafe, SettingsID) VALUES ('O', 'emoticons/emotion-31.gif', 'Time', 0, @SettingsID)
INSERT INTO cs_Smilies (SmileyCode, SmileyUrl, SmileyText, BracketSafe, SettingsID) VALUES ('sn', 'emoticons/emotion-32.gif', 'Snail', 0, @SettingsID)
INSERT INTO cs_Smilies (SmileyCode, SmileyUrl, SmileyText, BracketSafe, SettingsID) VALUES ('pi', 'emoticons/emotion-33.gif', 'Pizza', 0, @SettingsID)
INSERT INTO cs_Smilies (SmileyCode, SmileyUrl, SmileyText, BracketSafe, SettingsID) VALUES ('au', 'emoticons/emotion-34.gif', 'Automobile', 0, @SettingsID)
INSERT INTO cs_Smilies (SmileyCode, SmileyUrl, SmileyText, BracketSafe, SettingsID) VALUES ('um', 'emoticons/emotion-35.gif', 'Umbrella', 0, @SettingsID)
INSERT INTO cs_Smilies (SmileyCode, SmileyUrl, SmileyText, BracketSafe, SettingsID) VALUES ('co', 'emoticons/emotion-36.gif', 'Computer', 0, @SettingsID)
INSERT INTO cs_Smilies (SmileyCode, SmileyUrl, SmileyText, BracketSafe, SettingsID) VALUES ('st', 'emoticons/emotion-37.gif', 'Storm', 0, @SettingsID)
INSERT INTO cs_Smilies (SmileyCode, SmileyUrl, SmileyText, BracketSafe, SettingsID) VALUES ('mo', 'emoticons/emotion-38.gif', 'Moon', 0, @SettingsID)
INSERT INTO cs_Smilies (SmileyCode, SmileyUrl, SmileyText, BracketSafe, SettingsID) VALUES ('8o|', 'emoticons/emotion-39.gif', 'Super Angry', 0, @SettingsID)
INSERT INTO cs_Smilies (SmileyCode, SmileyUrl, SmileyText, BracketSafe, SettingsID) VALUES ('^o)', 'emoticons/emotion-40.gif', 'Hmm', 0, @SettingsID)
INSERT INTO cs_Smilies (SmileyCode, SmileyUrl, SmileyText, BracketSafe, SettingsID) VALUES ('+o(', 'emoticons/emotion-41.gif', 'Ick!', 0, @SettingsID)
INSERT INTO cs_Smilies (SmileyCode, SmileyUrl, SmileyText, BracketSafe, SettingsID) VALUES ('*-)', 'emoticons/emotion-42.gif', 'Confused', 0, @SettingsID)
INSERT INTO cs_Smilies (SmileyCode, SmileyUrl, SmileyText, BracketSafe, SettingsID) VALUES ('8-)', 'emoticons/emotion-43.gif', 'Confused', 0, @SettingsID)
INSERT INTO cs_Smilies (SmileyCode, SmileyUrl, SmileyText, BracketSafe, SettingsID) VALUES ('C', 'emoticons/emotion-44.gif', 'Coffee', 0, @SettingsID)
INSERT INTO cs_Smilies (SmileyCode, SmileyUrl, SmileyText, BracketSafe, SettingsID) VALUES ('N', 'emoticons/emotion-45.gif', 'No', 0, @SettingsID)
INSERT INTO cs_Smilies (SmileyCode, SmileyUrl, SmileyText, BracketSafe, SettingsID) VALUES ('D', 'emoticons/emotion-46.gif', 'Drinks', 0, @SettingsID)
INSERT INTO cs_Smilies (SmileyCode, SmileyUrl, SmileyText, BracketSafe, SettingsID) VALUES ('Z', 'emoticons/emotion-47.gif', 'Person', 0, @SettingsID)
INSERT INTO cs_Smilies (SmileyCode, SmileyUrl, SmileyText, BracketSafe, SettingsID) VALUES ('}', 'emoticons/emotion-48.gif', 'Right Hug', 0, @SettingsID)
INSERT INTO cs_Smilies (SmileyCode, SmileyUrl, SmileyText, BracketSafe, SettingsID) VALUES ('^', 'emoticons/emotion-49.gif', 'Cake', 0, @SettingsID)
INSERT INTO cs_Smilies (SmileyCode, SmileyUrl, SmileyText, BracketSafe, SettingsID) VALUES ('U', 'emoticons/emotion-50.gif', 'Broken Heart', 0, @SettingsID)
INSERT INTO cs_Smilies (SmileyCode, SmileyUrl, SmileyText, BracketSafe, SettingsID) VALUES ('G', 'emoticons/emotion-51.gif', 'Gift', 0, @SettingsID)
INSERT INTO cs_Smilies (SmileyCode, SmileyUrl, SmileyText, BracketSafe, SettingsID) VALUES ('W', 'emoticons/emotion-52.gif', 'Wilted Flower', 0, @SettingsID)
INSERT INTO cs_Smilies (SmileyCode, SmileyUrl, SmileyText, BracketSafe, SettingsID) VALUES ('~', 'emoticons/emotion-53.gif', 'Movie', 0, @SettingsID)
INSERT INTO cs_Smilies (SmileyCode, SmileyUrl, SmileyText, BracketSafe, SettingsID) VALUES ('&', 'emoticons/emotion-54.gif', 'Dog', 0, @SettingsID)
INSERT INTO cs_Smilies (SmileyCode, SmileyUrl, SmileyText, BracketSafe, SettingsID) VALUES ('I', 'emoticons/emotion-55.gif', 'Idea', 0, @SettingsID)
INSERT INTO cs_Smilies (SmileyCode, SmileyUrl, SmileyText, BracketSafe, SettingsID) VALUES ('S', 'emoticons/emotion-56.gif', 'Sleep', 0, @SettingsID)
INSERT INTO cs_Smilies (SmileyCode, SmileyUrl, SmileyText, BracketSafe, SettingsID) VALUES ('E', 'emoticons/emotion-57.gif', 'Email', 0, @SettingsID)
INSERT INTO cs_Smilies (SmileyCode, SmileyUrl, SmileyText, BracketSafe, SettingsID) VALUES ('ap', 'emoticons/emotion-58.gif', 'Travel', 0, @SettingsID)
INSERT INTO cs_Smilies (SmileyCode, SmileyUrl, SmileyText, BracketSafe, SettingsID) VALUES ('ip', 'emoticons/emotion-59.gif', 'Paradise', 0, @SettingsID)
INSERT INTO cs_Smilies (SmileyCode, SmileyUrl, SmileyText, BracketSafe, SettingsID) VALUES ('li', 'emoticons/emotion-60.gif', 'Lightning', 0, @SettingsID)

Declare @DeletedSectionID int
Declare @ReportingSectionID int

INSERT INTO cs_Groups 
	( [Name], [SortOrder], SettingsID, ApplicationType)
VALUES 
	( 'Administrators', 99999, @SettingsID, 0 )

Select @GroupID = @@Identity
Print 'Created Admin ForumGroup'

--Reporting Forum of Reporting Forum Type
Print 'Created Reporting Forum'
INSERT INTO 
	cs_Sections
	(
		SettingsID, ForumType, IsActive, ParentID, GroupID, Name, ApplicationKey, Description, DateCreated, Url, IsModerated, DaysToView, SortOrder, TotalPosts, TotalThreads, DisplayMask, EnablePostStatistics, EnablePostPoints, EnableAutoDelete, EnableAnonymousPosting, AutoDeleteThreshold, MostRecentPostID, MostRecentThreadID, MostRecentThreadReplies, MostRecentPostAuthor, MostRecentPostAuthorID, MostRecentPostDate, PostsToModerate, IsSearchable
	)
VALUES
	(
		@SettingsID, 60, 1, 0, @GroupID, 'Reporting Forums', 'Reporting_Forums-' + convert(nvarchar(10), @GroupID), 'When problems are reported they go in this forum.', GetDate(), '', 0, 7, 3, 0, 0, 0x0, 0, 0, 0, 1, 90, 0, 0, 0, '', 0, '1977-01-01', 0,  0
	)
Select @ReportingSectionID = @@Identity

Print 'Created Deleted Forum'
INSERT INTO 
	cs_Sections
	(
		SettingsID, ForumType, IsActive, ParentID, GroupID, Name, ApplicationKey, Description, DateCreated, Url, IsModerated, DaysToView, SortOrder, TotalPosts, TotalThreads, DisplayMask, EnablePostStatistics, EnablePostPoints, EnableAutoDelete, EnableAnonymousPosting, AutoDeleteThreshold, MostRecentPostID, MostRecentThreadID, MostRecentThreadReplies, MostRecentPostAuthor, MostRecentPostAuthorID, MostRecentPostDate, PostsToModerate, IsSearchable
	)
VALUES
	(
		@SettingsID, 50, 1, 0, @GroupID, 'Deleted Posts', 'Deleted_Posts-' + convert(nvarchar(10), @GroupID), 'Deleted posts are archived in this forum.', GetDate(), '', 0, 7, 4, 0, 0, 0x0, 0, 0, 0, 0, 90, 0, 0, 0, '', 0, '1977-01-01', 0, 0
	)
Select @DeletedSectionID = @@Identity



if(@IsApplicationCreated = 1)
Begin

	print 'Created default roles...'

	declare @EveryoneRoleID uniqueidentifier
	Set @EveryoneRoleID = newID()
	

	INSERT INTO [aspnet_Roles] ([RoleId], [ApplicationId], [RoleName], [LoweredRoleName], [Description]) VALUES (@EveryoneRoleID, @ApplicationID, N'Everyone', N'everyone', N'Do not add users to this role. This role exists only for permission mapping. All anonymous and registered users are automatically part of this role.')
	INSERT INTO [aspnet_Roles] ([RoleId], [ApplicationId], [RoleName], [LoweredRoleName], [Description]) VALUES (newID(), @ApplicationID, N'Registered Users', N'Registered Users', N'Users who create accounts are automatically added to this role.')
	INSERT INTO [aspnet_Roles] ([RoleId], [ApplicationId], [RoleName], [LoweredRoleName], [Description]) VALUES (newID(), @ApplicationID, N'Trusted Users', N'Trusted Users', N'Trusted users are given more permissions within the site.')
	INSERT INTO [aspnet_Roles] ([RoleId], [ApplicationId], [RoleName], [LoweredRoleName], [Description]) VALUES (newID(), @ApplicationID, N'Editor', N'editor', N'')
	INSERT INTO [aspnet_Roles] ([RoleId], [ApplicationId], [RoleName], [LoweredRoleName], [Description]) VALUES (newID(), @ApplicationID, N'Moderator', N'moderator', N'Moderators are allowed to approve content.')
	INSERT INTO [aspnet_Roles] ([RoleId], [ApplicationId], [RoleName], [LoweredRoleName], [Description]) VALUES (newID(), @ApplicationID, N'GalleryAdministrator', N'galleryadministrator', N'Administration role for Galleries.')
	INSERT INTO [aspnet_Roles] ([RoleId], [ApplicationId], [RoleName], [LoweredRoleName], [Description]) VALUES (newID(), @ApplicationID, N'ForumsAdministrator', N'forumsadministrator', N'Administration role for Forums.')
	INSERT INTO [aspnet_Roles] ([RoleId], [ApplicationId], [RoleName], [LoweredRoleName], [Description]) VALUES (newID(), @ApplicationID, N'BlogAdministrator', N'blogadministrator', N'Administration role for Blogs')
	INSERT INTO [aspnet_Roles] ([RoleId], [ApplicationId], [RoleName], [LoweredRoleName], [Description]) VALUES (newID(), @ApplicationID, N'ReaderAdministrator', N'readeradministrator', N'Administration role for the Feed Reader')
	INSERT INTO [aspnet_Roles] ([RoleId], [ApplicationId], [RoleName], [LoweredRoleName], [Description]) VALUES (newID(), @ApplicationID, N'ReaderUser', N'readeruser', N'Users who are allowed to use the Feed Reader')
	INSERT INTO [aspnet_Roles] ([RoleId], [ApplicationId], [RoleName], [LoweredRoleName], [Description]) VALUES (newID(), @ApplicationID, N'FileAdministrator', N'fileadministrator', N'Administration role for Files')
	INSERT INTO [aspnet_Roles] ([RoleId], [ApplicationId], [RoleName], [LoweredRoleName], [Description]) VALUES (newID(), @ApplicationID, N'MembershipAdministrator', N'membershipadministrator', N'Administration role for Member Management')
	INSERT INTO [aspnet_Roles] ([RoleId], [ApplicationId], [RoleName], [LoweredRoleName], [Description]) VALUES (newID(), @ApplicationID, N'SystemAdministrator', N'systemadministrator', N'Global Administration role.')	
	INSERT INTO [aspnet_Roles] ([RoleId], [ApplicationId], [RoleName], [LoweredRoleName], [Description]) VALUES (newID(), @ApplicationID, N'Owners', N'owners', N'Owners are the role used for bloggers and photogallery owners')

	Declare @UserID uniqueidentifier
	Declare @cs_UserID int
	
	if(@AdminUserName is not null)
	Begin

		Set @UserID = newid()
		
		Print 'Create Admin User'
		INSERT INTO [aspnet_Users] ([UserId], [ApplicationId], [UserName], [LoweredUserName], [MobileAlias], [IsAnonymous], [LastActivityDate]) 
		      VALUES (@UserID, @ApplicationID, @AdminUserName, Lower(@AdminUserName), NULL, 0, getdate())
		--Do we need to make Salt configurable?
		INSERT INTO [aspnet_Membership] ([ApplicationId], [UserId], [Password],     [PasswordFormat], [PasswordSalt],              [MobilePIN], [Email], [LoweredEmail], [PasswordQuestion], [PasswordAnswer], [IsApproved], [CreateDate], [LastLoginDate], [LastPasswordChangedDate], [Comment], FailedPasswordAnswerAttemptWindowStart, FailedPasswordAnswerAttemptCount, FailedPasswordAttemptWindowStart, FailedPasswordAttemptCount, LastLockoutDate, IsLockedOut) 
					 VALUES (@ApplicationID, @UserID,  @AdminPassword, @PasswordFormat,   N'DVZTktxeMzDtXR7eik7Cdw==', NULL,       @AdminEmail,    NULL,            NULL,               NULL,            1,            getdate(),    getdate(),       getdate(),                 NULL,                 '1753-01-01',                              0,                               '1753-01-01',                       0,                          '1753-01-01',      0)
		
		INSERT INTO [cs_Users]([MembershipID], [ForceLogin], [UserAccountStatus], [AppUserToken], [LastActivity], [LastAction])
		VALUES(@UserID, 0,1, null, getdate(), '')


		Set @cs_UserID = @@Identity
		
		INSERT INTO [cs_UserProfile]([UserID], [TimeZone], [TotalPosts], [PostSortOrder], [PostRank], [IsAvatarApproved], [ModerationLevel], [EnableThreadTracking], [EnableDisplayUnreadThreadsOnly], [EnableAvatar], [EnableDisplayInMemberList], [EnablePrivateMessages], [EnableOnlineStatus], [EnableHtmlEmail], [MembershipID], [SettingsID], [PropertyNames], [PropertyValues])
		VALUES (@cs_UserID, 0, 0, 0, 0x01, 0, 0, 0, 0, 0, 0, 0, 1, 0, @UserID, @SettingsID, NULL, NULL)
		
		Print 'Created Admin User'
		
		Insert aspnet_UsersInRoles (UserId, RoleId) 
		Select @UserID, RoleId FROM aspnet_Roles where ApplicationId = @ApplicationID
	
	End
	
	
	Set @UserID = newid()
	
	Print 'Create Anonymous User'
	INSERT INTO [aspnet_Users] ([UserId], [ApplicationId], [UserName], [LoweredUserName], [MobileAlias], [IsAnonymous], [LastActivityDate]) 
	      VALUES (@UserID, @ApplicationID, 'Anonymous', Lower('Anonymous'), NULL, 1, getdate())
	--Do we need to make Salt configurable?
	INSERT INTO [aspnet_Membership] ([ApplicationId],[UserId], [Password],     [PasswordFormat], [PasswordSalt],              [MobilePIN], [Email],						[LoweredEmail], [PasswordQuestion], [PasswordAnswer], [IsApproved], [CreateDate], [LastLoginDate], [LastPasswordChangedDate], [Comment],	[FailedPasswordAnswerAttemptWindowStart], [FailedPasswordAnswerAttemptCount],	[FailedPasswordAttemptWindowStart], [FailedPasswordAttemptCount],	[LastLockoutDate],	[IsLockedOut])
	                         VALUES (@ApplicationID, @UserID,  @UserID,         0,               N'DVZTktxeMzDtXR7eik7Cdw==', NULL,        'anonymous@localhost.com',    NULL,            NULL,               NULL,            1,            getdate(),    getdate(),       getdate(),                 NULL,			'1753-01-01',                              0,									'1753-01-01',                       0,								'1753-01-01',		0)
	
	INSERT INTO [cs_Users]([MembershipID], [ForceLogin], [UserAccountStatus], [AppUserToken], [LastActivity], [LastAction])
	VALUES(@UserID, 0,1, null, getdate(), '')

	Set @cs_UserID = @@Identity
	
	INSERT INTO [cs_UserProfile]([UserID], [TimeZone], [TotalPosts], [PostSortOrder], [PostRank], [IsAvatarApproved], [ModerationLevel], [EnableThreadTracking], [EnableDisplayUnreadThreadsOnly], [EnableAvatar], [EnableDisplayInMemberList], [EnablePrivateMessages], [EnableOnlineStatus], [EnableHtmlEmail], [MembershipID], [SettingsID], [PropertyNames], [PropertyValues])
	VALUES                          (@cs_UserID, 0, 0, 0, 0x01, 0, 0, 0, 0, 0, 0, 0, 1, 0, @UserID, @SettingsID, NULL, NULL)

	-- add the anonymous user to the everyone role
	INSERT INTO aspnet_UsersInRoles ([UserId], [RoleId]) VALUES( @UserID, @EveryoneRoleID )
END
ELSE
BEGIN
	Print 'Copied CS_UserProfile'
	--Import ApplicationID specific users from aspnet_Users if they dont already exists

	INSERT INTO [cs_Users]([MembershipID], [ForceLogin], [UserAccountStatus], [AppUserToken], [LastActivity], [LastAction])
	SELECT aspnet.UserId, 0,1, null, getdate(), '' from dbo.vw_aspnet_MembershipUsers aspnet LEFT OUTER JOIN dbo.cs_vw_Users_FullUser cs on aspnet.UserId = cs.UserId WHERE aspnet.ApplicationId = @ApplicationID and cs.UserId is null

	--Create cs_UserProfile records for any cs_Users without Profiles

	INSERT INTO [cs_UserProfile]([UserID], [TimeZone], [TotalPosts], [PostSortOrder], [PostRank], [IsAvatarApproved], [ModerationLevel], [EnableThreadTracking], [EnableDisplayUnreadThreadsOnly], [EnableAvatar], [EnableDisplayInMemberList], [EnablePrivateMessages], [EnableOnlineStatus], [EnableHtmlEmail], [MembershipID], [SettingsID], [PropertyNames], [PropertyValues])
	SELECT cs_Users.UserID, 0, 0, 0, 0x01, 0, 0, 0, 0, 0, 0, 0, 1, 0, cs_Users.MembershipID, @SettingsID, NULL, NULL FROM cs_Users LEFT OUTER JOIN cs_UserProfile on cs_Users.UserID = cs_UserProfile.UserID and cs_UserProfile.SettingsID = @SettingsID Where cs_UserProfile.UserID is null and cs_Users.MembershipID in (Select UserId FROM aspnet_Users where ApplicationId = @ApplicationID)

END

Declare @Perm_RoleID uniqueidentifier

	-- These items need to be set outside the if(@IsApplicationCreated = 1) since they need to be created based on the SettingsID and not ApplicationID


	Select @Perm_RoleID = RoleId from aspnet_Roles where ApplicationId = @ApplicationID and RoleName = 'Everyone'
	INSERT INTO [cs_ProductPermissions] ([SettingsID], [ApplicationType], [RoleID], [AllowMask], [DenyMask]) values (@SettingsID, 0, @Perm_RoleID, 0x000000000000000F, 0x00001007000000F0 ) -- Forum Permission
	INSERT INTO [cs_ProductPermissions] ([SettingsID], [ApplicationType], [RoleID], [AllowMask], [DenyMask]) values (@SettingsID, 1, @Perm_RoleID, 0x0000000000000009, 0x0000000000000004 ) -- Weblog Permission  >> Allow View, Reply  Deny Post
	INSERT INTO [cs_ProductPermissions] ([SettingsID], [ApplicationType], [RoleID], [AllowMask], [DenyMask]) values (@SettingsID, 2, @Perm_RoleID, 0x0000000000000089, 0xFFFFFFFFFFFFFF76 ) -- Gallery Permission
	INSERT INTO [cs_ProductPermissions] ([SettingsID], [ApplicationType], [RoleID], [AllowMask], [DenyMask]) values (@SettingsID, 3, @Perm_RoleID, 0x0000000000000001, 0x000000000000000C ) -- GuestBook Permission  >> Allow View,  Deny Post, Reply
	INSERT INTO [cs_ProductPermissions] ([SettingsID], [ApplicationType], [RoleID], [AllowMask], [DenyMask]) values (@SettingsID, 6, @Perm_RoleID, 0x000000000000000B, 0x00001000000000B4 ) -- File Permission >> Allow  View, Read, Replay, Deny Post, Moderate, Vote, Delete, Edit
	-- SET SPECIFIC DELETED adn Reporting Forums Permission	
	INSERT INTO [cs_SectionPermissions] ([SettingsID], [SectionID], [RoleID], [AllowMask], [DenyMask]) values( @SettingsID, @ReportingSectionID, @Perm_RoleID, 0x0, -1 )
	INSERT INTO [cs_SectionPermissions] ([SettingsID], [SectionID], [RoleID], [AllowMask], [DenyMask]) values( @SettingsID, @DeletedSectionID, @Perm_RoleID, 0x0, -1 )

	Select @Perm_RoleID = RoleId from aspnet_Roles where ApplicationId = @ApplicationID and RoleName = 'Registered Users'
	INSERT INTO [cs_ProductPermissions] ([SettingsID], [ApplicationType], [RoleID], [AllowMask], [DenyMask]) values (@SettingsID, 0, @Perm_RoleID, 0x00000000000000BF, 0 )
	INSERT INTO [cs_ProductPermissions] ([SettingsID], [ApplicationType], [RoleID], [AllowMask], [DenyMask]) values (@SettingsID, 1, @Perm_RoleID, 0x0000000000000009, 0x0000000000000004 ) -- Weblog Permission  >> Allow View, Reply  Deny Post
	INSERT INTO [cs_ProductPermissions] ([SettingsID], [ApplicationType], [RoleID], [AllowMask], [DenyMask]) values (@SettingsID, 2, @Perm_RoleID, 0x00000000000000B9, 0 ) -- Gallery Permission
	INSERT INTO [cs_ProductPermissions] ([SettingsID], [ApplicationType], [RoleID], [AllowMask], [DenyMask]) values (@SettingsID, 6, @Perm_RoleID, 0x000000000000008B, 0x0000100000000030 ) -- File Permission

	INSERT INTO [cs_ProductPermissions] ([SettingsID], [ApplicationType], [RoleID], [AllowMask], [DenyMask]) values (@SettingsID, 3, @Perm_RoleID, 0x0000000000000009, 0x0000000000000004 ) -- GuestBook Permission  >> Allow View, Reply  Deny Post
	-- SET SPECIFIC DELETED adn Reporting Forums Permission	
	INSERT INTO [cs_SectionPermissions] ([SettingsID], [SectionID], [RoleID], [AllowMask], [DenyMask]) values( @SettingsID, @ReportingSectionID, @Perm_RoleID, 0x0, -1 )
	INSERT INTO [cs_SectionPermissions] ([SettingsID], [SectionID], [RoleID], [AllowMask], [DenyMask]) values( @SettingsID, @DeletedSectionID, @Perm_RoleID, 0x0, -1 )
	
	Select @Perm_RoleID = RoleId from aspnet_Roles where ApplicationId = @ApplicationID and RoleName = 'Editor'
	INSERT INTO [cs_ProductPermissions] ([SettingsID], [ApplicationType], [RoleID], [AllowMask], [DenyMask]) values (@SettingsID, 0, @Perm_RoleID, 0x0000000F000000FF, 0 )
	INSERT INTO [cs_ProductPermissions] ([SettingsID], [ApplicationType], [RoleID], [AllowMask], [DenyMask]) values (@SettingsID, 6, @Perm_RoleID, 0x00000000000002FF, 0x0000100000000000 ) -- File Permission

	-- SET SPECIFIC DELETED Forums Permission
	INSERT INTO [cs_SectionPermissions] ([SettingsID], [SectionID], [RoleID], [AllowMask], [DenyMask]) values( @SettingsID, @DeletedSectionID, @Perm_RoleID, 0x0, -1 )

	Select @Perm_RoleID = RoleId from aspnet_Roles where ApplicationId = @ApplicationID and RoleName = 'Moderator'
	INSERT INTO [cs_ProductPermissions] ([SettingsID], [ApplicationType], [RoleID], [AllowMask], [DenyMask]) values (@SettingsID, 0, @Perm_RoleID, 0x0000100F00000FFF, 0 )
	INSERT INTO [cs_ProductPermissions] ([SettingsID], [ApplicationType], [RoleID], [AllowMask], [DenyMask]) values (@SettingsID, 6, @Perm_RoleID, 0x00001000000002CF, 0x0000000000000030 ) -- File Permission

	Select @Perm_RoleID = RoleId from aspnet_Roles where ApplicationId = @ApplicationID and RoleName = 'GalleryAdministrator'
	INSERT INTO [cs_ProductPermissions] ([SettingsID], [ApplicationType], [RoleID], [AllowMask], [DenyMask]) values (@SettingsID, 2, @Perm_RoleID, 0x01001000000000BD, 0 ) -- Gallery Permission
	
		Select @Perm_RoleID = RoleId from aspnet_Roles where ApplicationId = @ApplicationID and RoleName = 'FileAdministrator'
	INSERT INTO [cs_ProductPermissions] ([SettingsID], [ApplicationType], [RoleID], [AllowMask], [DenyMask]) values (@SettingsID, 6, @Perm_RoleID, 0x01001008000002FF, 0 ) -- File Permission

	Select @Perm_RoleID = RoleId from aspnet_Roles where ApplicationId = @ApplicationID and RoleName = 'ForumsAdministrator'
	INSERT INTO [cs_ProductPermissions] ([SettingsID], [ApplicationType], [RoleID], [AllowMask], [DenyMask]) values (@SettingsID, 0, @Perm_RoleID, 0x0100100F00000FFF, 0 )

	Select @Perm_RoleID = RoleId from aspnet_Roles where ApplicationId = @ApplicationID and RoleName = 'BlogAdministrator'
	INSERT INTO [cs_ProductPermissions] ([SettingsID], [ApplicationType], [RoleID], [AllowMask], [DenyMask]) values (@SettingsID, 1, @Perm_RoleID, 0x000000000000024D, 0 ) -- Weblog Permission  >> Allow View, Reply, Post

	Select @Perm_RoleID = RoleId from aspnet_Roles where ApplicationId = @ApplicationID and RoleName = 'SystemAdministrator'
	INSERT INTO [cs_ProductPermissions] ([SettingsID], [ApplicationType], [RoleID], [AllowMask], [DenyMask]) values (@SettingsID, 0, @Perm_RoleID, 0x4100100F00000FFF, 0 )
	INSERT INTO [cs_ProductPermissions] ([SettingsID], [ApplicationType], [RoleID], [AllowMask], [DenyMask]) values (@SettingsID, 1, @Perm_RoleID, 0x000000000000024D, 0 ) -- Weblog Permission >> Allow View, Reply, Post
	INSERT INTO [cs_ProductPermissions] ([SettingsID], [ApplicationType], [RoleID], [AllowMask], [DenyMask]) values (@SettingsID, 2, @Perm_RoleID, 0x41001000000000BD, 0 ) -- Gallery Permission
	INSERT INTO [cs_ProductPermissions] ([SettingsID], [ApplicationType], [RoleID], [AllowMask], [DenyMask]) values (@SettingsID, 6, @Perm_RoleID, 0x41001008000002FF, 0 ) -- File Permission

	Select @Perm_RoleID = RoleId from aspnet_Roles where ApplicationId = @ApplicationID and RoleName = 'Owners'
	INSERT INTO [cs_ProductPermissions] ([SettingsID], [ApplicationType], [RoleID], [AllowMask], [DenyMask]) values (@SettingsID, 1, @Perm_RoleID, 0x000000000000024D, 0 ) -- Weblog Permission >> Allow View, Reply, Post, and Attachments
	INSERT INTO [cs_ProductPermissions] ([SettingsID], [ApplicationType], [RoleID], [AllowMask], [DenyMask]) values (@SettingsID, 2, @Perm_RoleID, 0x41001000000000BD, 0 ) -- Gallery Permission
	INSERT INTO [cs_ProductPermissions] ([SettingsID], [ApplicationType], [RoleID], [AllowMask], [DenyMask]) values (@SettingsID, 6, @Perm_RoleID, 0x01001008000002FF, 0 ) -- File Permission


---Return New Data	

if @CreateSamples = 1
Begin
	exec cs_system_SampleGallery @SettingsID, @AdminUserName
	exec cs_system_SampleWeblog @SettingsID, @AdminUserName
	exec cs_system_SampleForum @SettingsID, @AdminUserName
	exec cs_system_SampleDownload @SettingsID, @AdminUserName
End

--Select * FROM cs_Sites
--DELETE FROM cs_Sites where ApplicationID > 50
Select * FROM aspnet_Applications where ApplicationId = @ApplicationID
Select * FROM aspnet_Users where ApplicationId = @ApplicationID
Select * FROM aspnet_Membership where UserId in (Select UserId FROM aspnet_Users where ApplicationId = @ApplicationID)
Select * FROM cs_UserProfile where SettingsID = @SettingsID
Select * FROM cs_Sites where SiteID = @SiteID
Select * FROM cs_SiteSettings where SettingsID = @SettingsID
Select * FROM cs_SiteMappings where SettingsID = @SettingsID and SiteID = @SiteID
Select * FROM cs_ProductPermissions where SettingsID = @SettingsID
Select * FROM cs_SectionPermissions where SettingsID = @SettingsID
Go

grant execute on [dbo].[cs_system_CreateCommunity] to public
go
/***********************************************
* Sproc: cs_system_DeletePostAndAdoptChildren
* File Date: 11/29/2006 10:07:31 AM
***********************************************/
Print 'Creating...cs_system_DeletePostAndAdoptChildren'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO


if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_system_DeletePostAndAdoptChildren]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_system_DeletePostAndAdoptChildren]
GO


CREATE procedure [dbo].cs_system_DeletePostAndAdoptChildren
(
	@PostID int,
	@SettingsID int,
	@DeletedBy INT,
	@Reason NVARCHAR(1024) = '',
	@NewThreadID int = NULL OUT
)
AS
-- Deleted Post is really moved to "Deleted Posts" forum (ForumType = 50)

SET Transaction Isolation Level Read UNCOMMITTED
BEGIN

DECLARE @OldThreadID INT
DECLARE @UserID INT
DECLARE @PostAuthor NVARCHAR(64)
DECLARE @SectionID INT
DECLARE @ParentID INT
DECLARE @IsApproved BIT
DECLARE @PostDate DATETIME
DECLARE @EmoticonID INT
DECLARE @IsLocked INT
DECLARE @DeletedSectionID INT
DECLARE @HasReplies INT
DECLARE @OldPostLevel INT
DECLARE @PostLevel INT
DECLARE @SortOrder INT

-- First, get information about the post that is about to be deleted.
------------------------------------------------------------------------------------------
SELECT @DeletedSectionID = SectionID FROM cs_Sections WHERE SettingsID = @SettingsID and ForumType = 50

SET @HasReplies = (SELECT COUNT(*) FROM cs_Posts WHERE ParentID = @PostID AND SettingsID = @SettingsID)

SELECT
	@OldThreadID = ThreadID,
	@OldPostLevel = PostLevel,
	@UserID = UserID,
	@PostAuthor = PostAuthor,
	@ParentID = ParentID,
	@SectionID = SectionID,
	@IsLocked = IsLocked,
	@IsApproved = IsApproved,
	@PostDate = PostDate,
	@EmoticonID = EmoticonID
FROM
	cs_Posts
WHERE
	PostID = @PostID AND 
	SettingsID = @SettingsID
------------------------------------------------------------------------------------------
print @parentid

-- Stop here if the post is not approved
IF (@IsApproved = 0)
BEGIN
	RETURN 1
END

-- This proc should only be called from non-thread starting posts
IF (@OldPostLevel <> 1)
BEGIN
	-- We create a new thread here because we won't move the whole thread.
	-- The new thread will clone current thread.
	------------------------------------------------------------------------------------------
	IF (@NewThreadID IS NULL)
	BEGIN
		INSERT cs_Threads
		(
			SectionID,
			PostDate,
			UserID,
			PostAuthor,
			ThreadDate,
			MostRecentPostAuthor,
			MostRecentPostAuthorID,
			MostRecentPostID,
			IsLocked,
			IsApproved,
			IsSticky,
			StickyDate,
			ThreadEmoticonID,
			SettingsID
		)
		VALUES
		(
			@DeletedSectionID,	-- the Deleted Posts forum
			@PostDate,
			@UserID,
			@PostAuthor,
			@PostDate,
			@PostAuthor,
			@UserID,
			@PostID,	-- MostRecentPostID, which we don't know until after post INSERT below.
			@IsLocked,
			@IsApproved,
			0,	-- Downgrade the thread to a non-sticky.
			@PostDate,
			@EmoticonID,
			@SettingsID
		)
		
		-- Get the new ThreadID
		SET @NewThreadID = @@IDENTITY
	END

	-- First delete this post which is a parent post and should have its children adopted
	------------------------------------------------------------------------------------------
	-- Posts related updates
	UPDATE cs_PostAttachments SET SectionID = @DeletedSectionID WHERE PostID = @PostID

	UPDATE
		cs_Posts
	SET
		SectionID = @DeletedSectionID,
		PostLevel = 1,
		ThreadID = @NewThreadID,
		ParentID = @PostID,
		SortOrder = 1
	WHERE
		PostID = @PostID AND
		SettingsID = @SettingsID

	-- Update the search index
	UPDATE cs_SearchBarrel SET ThreadID = @NewThreadID WHERE PostID = @PostID AND ThreadID = @OldThreadID AND SettingsID = @SettingsID

	-- Update Moderation Audit table
	IF (@Reason IS NULL OR @Reason = '')
		SET @Reason = 'Automatic generated reason: the post has been deleted on request.'

	EXEC cs_system_ModerationAction_AuditEntry 4, @DeletedBy, @PostID, null, null, @SettingsID, @Reason
	------------------------------------------------------------------------------------------

	-- Are there children to be adopted?
	------------------------------------------------------------------------------------------
	IF (@HasReplies > 0)
	BEGIN

print 'adopt children'
		-- Adopt children (by grandparent)
		UPDATE	cs_Posts
		SET		ParentID = @ParentID,
				PostLevel = @OldPostLevel
		WHERE	ParentID = @PostID AND
				ThreadID = @OldThreadID AND
				SectionID = @SectionID AND
				SettingsID = @SettingsID

		-- Get max post level (used for looping)
		DECLARE	@MaxPostLevel	INT
		SELECT	@MaxPostLevel = MAX(PostLevel)
		FROM	cs_Posts
		WHERE	ThreadID = @OldThreadID AND
				SectionID = @SectionID AND
				SettingsID = @SettingsID

		DECLARE	@level	int
		SET		@level = @OldPostLevel

		-- loop thru posting levels and recalculate (should just be a decrement)
		WHILE (@level <= @MaxPostLevel)
		BEGIN
			print 'reset levels'
			UPDATE	P
			SET		P.PostLevel = PP.PostLevel + 1
			FROM	cs_Posts P INNER JOIN cs_Posts PP ON P.ParentID = PP.PostID
			WHERE	P.PostLevel = @level AND
					P.ThreadID = @OldThreadID AND
					P.SectionID = @SectionID AND
					P.SettingsID = @SettingsID

			SET	@level = @level + 1
		END
	END
	------------------------------------------------------------------------------------------

	RETURN 1
END	

END
		
/*
	-- Decrease the TotalPosts on the user's profile.
	IF (SELECT EnablePostStatistics FROM cs_Sections WHERE SectionID = @SectionID and SettingsID = @SettingsID) = 1
		UPDATE 
			cs_UserProfile
		SET 
			TotalPosts = ISNULL(TotalPosts - (SELECT COUNT(PostID) FROM cs_Posts WHERE ThreadID = @ThreadID and SettingsID = @SettingsID), 0)
		WHERE 
			UserID = @UserID and SettingsID = @SettingsID

*/

GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO


grant execute on [dbo].[cs_system_DeletePostAndAdoptChildren] to public
go
/***********************************************
* Sproc: cs_system_DeletePostAndChildren
* File Date: 11/29/2006 10:07:29 AM
***********************************************/
Print 'Creating...cs_system_DeletePostAndChildren'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO


if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_system_DeletePostAndChildren]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_system_DeletePostAndChildren]
GO


CREATE procedure [dbo].cs_system_DeletePostAndChildren
(
	@PostID int,
	@DeleteChildren bit = 1,
	@SettingsID int,
	@DeletedBy INT,
	@Reason NVARCHAR(1024) = '',
	@NewThreadID int = NULL OUT,
	@NewPostLevel int = NULL
)
AS
-- Posts are not "deleted", but they are moved to SectionID=4.
-- Start deleting with @NewPostLevel being NULL

SET Transaction Isolation Level Read UNCOMMITTED
BEGIN

DECLARE @OldThreadID INT
DECLARE @UserID INT
DECLARE @PostAuthor NVARCHAR(64)
DECLARE @SectionID INT
DECLARE @ParentID INT
DECLARE @IsApproved BIT
DECLARE @PostDate DATETIME
DECLARE @EmoticonID INT
DECLARE @IsLocked INT
DECLARE @DeletedSectionID INT
DECLARE @HasReplies INT
DECLARE @OldPostLevel INT
DECLARE @PostLevel INT
DECLARE @SortOrder INT

-- First, get information about the post that is about to be deleted.
------------------------------------------------------------------------------------------
SELECT @DeletedSectionID = SectionID FROM cs_Sections WHERE SettingsID = @SettingsID and ForumType = 50

SET @HasReplies = (SELECT COUNT(*) FROM cs_Posts WHERE ParentID = @PostID AND SettingsID = @SettingsID)

SELECT
	@OldThreadID = ThreadID,
	@OldPostLevel = PostLevel,
	@UserID = UserID,
	@PostAuthor = PostAuthor,
	@ParentID = ParentID,
	@SectionID = SectionID,
	@IsLocked = IsLocked,
	@IsApproved = IsApproved,
	@PostDate = PostDate,
	@EmoticonID = EmoticonID
FROM
	cs_Posts
WHERE
	PostID = @PostID AND 
	SettingsID = @SettingsID
------------------------------------------------------------------------------------------

-- Stop here if the post is not approved
IF (@IsApproved = 0)
BEGIN
	RETURN 1
END

IF (@OldPostLevel = 1)
BEGIN		
	-- We may "move" the whole thread. So update and delete some records.
	------------------------------------------------------------------------------------------
	-- Posts related updates								
	UPDATE cs_PostAttachments SET SectionID = @DeletedSectionID WHERE PostID IN (SELECT PostID FROM cs_Posts WHERE ThreadID = @OldThreadID AND SettingsID = @SettingsID)

	UPDATE cs_Posts SET SectionID = @DeletedSectionID WHERE ThreadID = @OldThreadID AND SettingsID = @SettingsID

	-- Threads related updates
	UPDATE cs_ThreadsRead SET SectionID = @DeletedSectionID WHERE ThreadID = @OldThreadID AND SettingsID = @SettingsID

	DELETE FROM cs_TrackedThreads WHERE ThreadID = @OldThreadID AND SettingsID = @SettingsID

	UPDATE cs_Threads SET SectionID = @DeletedSectionID WHERE ThreadID = @OldThreadID AND SettingsID = @SettingsID

	-- Delete from the search index
	DELETE cs_SearchBarrel WHERE ThreadID = @OldThreadID AND SettingsID = @SettingsID
	
	EXEC cs_system_ModerationAction_AuditEntry 4, @DeletedBy, @PostID, null, null, @SettingsID, @Reason
		
	RETURN 1
	------------------------------------------------------------------------------------------
END
ELSE
BEGIN
	-- We create a new thread here because we won't move the whole thread.
	-- The new thread will clone current thread.
	------------------------------------------------------------------------------------------
	IF (@NewThreadID IS NULL)
	BEGIN
		INSERT cs_Threads 	
		( 
			SectionID,
			PostDate, 
			UserID, 
			PostAuthor, 
			ThreadDate, 
			MostRecentPostAuthor, 
			MostRecentPostAuthorID, 	
			MostRecentPostID, 
			IsLocked, 
			IsApproved,
			IsSticky, 
			StickyDate, 
			ThreadEmoticonID,
			SettingsID 
		)
		VALUES
		( 
			@DeletedSectionID, 	-- the Deleted Posts forum
			@PostDate, 
			@UserID, 
			@PostAuthor,
			@PostDate,
			@PostAuthor,
			@UserID, 
			@PostID,	-- MostRecentPostID, which we don't know until after post INSERT below.
			@IsLocked,
			@IsApproved,
			0,	-- Downgrade the thread to a non-sticky.
			@PostDate,
			@EmoticonID,
			@SettingsID 
		)
		
		-- Get the new ThreadID
		SET @NewThreadID = @@IDENTITY		
	END
	------------------------------------------------------------------------------------------
		
	-- Calculate Post Level, Parent ID & Sort Order values
	------------------------------------------------------------------------------------------
	IF (@NewPostLevel IS NULL)
	BEGIN
		-- We have an unknown post level, so we have to figure out its values
		IF (NOT EXISTS(SELECT PostID FROM cs_Posts WHERE ThreadID = @NewThreadID AND SettingsID = @SettingsID AND SectionID = @DeletedSectionID))
		BEGIN
			-- Set this post as a tread starter post
			SET @NewPostLevel = 1					
			SET @ParentID = @PostID
			SET @SortOrder = 1
		END
		ELSE
		BEGIN				
			-- Bind this post to the thread starter post
			SET @NewPostLevel = 2
			SET @SortOrder = (SELECT MAX(SortOrder) + 1 FROM cs_Posts WHERE ThreadID = @NewThreadID AND SettingsID = @SettingsID AND SectionID = @DeletedSectionID)
		END
		
		-- Set children's post level
		SET @PostLevel = (@NewPostLevel + 1)
	END
	ELSE
	BEGIN
		--SET @PostLevel = 2
		SET @PostLevel = (@NewPostLevel + 1)
		SET @SortOrder = (SELECT MAX(SortOrder) + 1 FROM cs_Posts WHERE ThreadID = @NewThreadID AND SettingsID = @SettingsID AND SectionID = @DeletedSectionID)
	END
	------------------------------------------------------------------------------------------

	-- First delete this post which is a parent post and should have its children removed
	------------------------------------------------------------------------------------------
	-- Posts related updates								
	UPDATE cs_PostAttachments SET SectionID = @DeletedSectionID WHERE PostID = @PostID
		
	UPDATE 
		cs_Posts 
	SET 
		SectionID = @DeletedSectionID, 
		PostLevel = @NewPostLevel, 
		ThreadID = @NewThreadID,
		ParentID = @ParentID,
		SortOrder = @SortOrder
	WHERE 
		PostID = @PostID AND 
		SettingsID = @SettingsID
		
	-- TODO: Threads related updates?!
		
	-- Update the search index
	UPDATE cs_SearchBarrel SET ThreadID = @NewThreadID WHERE PostID = @PostID AND ThreadID = @OldThreadID AND SettingsID = @SettingsID
		
	-- Update Moderation Audit table
	IF (@Reason IS NULL OR @Reason = '')
		SET @Reason = 'Automatic generated reason: the post has been deleted on request.'
		
	EXEC cs_system_ModerationAction_AuditEntry 4, @DeletedBy, @PostID, null, null, @SettingsID, @Reason
	------------------------------------------------------------------------------------------

	-- Are we allowed to delete children and there are some?
	------------------------------------------------------------------------------------------
	IF (@DeleteChildren = 1 AND @HasReplies > 0)
	BEGIN
		DECLARE @CurrentPostID INT

		-- Delete replying posts through a cursor loop
		DECLARE Posts_Cursor CURSOR LOCAL FORWARD_ONLY FOR
		SELECT 
			PostID 
		FROM
			cs_Posts
		WHERE
			ParentID = @PostID AND
			ThreadID = @OldThreadID AND
			SectionID = @SectionID AND
			SettingsID = @SettingsID
	
		OPEN Posts_Cursor
			
		FETCH NEXT FROM Posts_Cursor INTO @CurrentPostID
	
		WHILE (@@FETCH_STATUS = 0)
		BEGIN
			-- Recursively call
			EXEC cs_system_DeletePostAndChildren @CurrentPostID, @DeleteChildren, @SettingsID, @DeletedBy, @Reason, @NewThreadID OUT, @PostLevel
	
			FETCH NEXT FROM Posts_Cursor INTO @CurrentPostID
		END
	
		CLOSE Posts_Cursor
	
		DEALLOCATE Posts_Cursor		
	END
	------------------------------------------------------------------------------------------

	RETURN 1
END	

END
		
/*
	-- Decrease the TotalPosts on the user's profile.
	IF (SELECT EnablePostStatistics FROM cs_Sections WHERE SectionID = @SectionID and SettingsID = @SettingsID) = 1
		UPDATE 
			cs_UserProfile
		SET 
			TotalPosts = ISNULL(TotalPosts - (SELECT COUNT(PostID) FROM cs_Posts WHERE ThreadID = @ThreadID and SettingsID = @SettingsID), 0)
		WHERE 
			UserID = @UserID and SettingsID = @SettingsID

*/

GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO


grant execute on [dbo].[cs_system_DeletePostAndChildren] to public
go
/***********************************************
* Sproc: cs_system_DuplicatePost
* File Date: 11/29/2006 10:07:31 AM
***********************************************/
Print 'Creating...cs_system_DuplicatePost'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_system_DuplicatePost]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_system_DuplicatePost]
GO





create procedure [dbo].cs_system_DuplicatePost
(
@UserID int,
@Body ntext,
@IntervalInMinutes int = 0,
@SettingsID int,
@IsDuplicate bit out
)
AS
SET Transaction Isolation Level Read UNCOMMITTED

	IF @IntervalInMinutes > 0
		-- Check for duplicates
		IF EXISTS (SELECT TOP 1 PostID FROM cs_Posts (nolock) WHERE SettingsID = @SettingsID and  UserID = @UserID AND Body LIKE @Body AND PostDate > DateAdd(minute, -@IntervalInMinutes, GetDate()) )
			SET @IsDuplicate = 1
		ELSE
			SET @IsDuplicate = 0
        ELSE
		-- Check for duplicates
		IF EXISTS (SELECT TOP 1 PostID FROM cs_Posts (nolock) WHERE SettingsID = @SettingsID and  UserID = @UserID AND Body LIKE @Body)
			SET @IsDuplicate = 1
		ELSE
			SET @IsDuplicate = 0









GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_system_DuplicatePost] to public
go
/***********************************************
* Sproc: cs_system_ModerationAction_AuditEntry
* File Date: 11/29/2006 10:07:33 AM
***********************************************/
Print 'Creating...cs_system_ModerationAction_AuditEntry'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_system_ModerationAction_AuditEntry]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_system_ModerationAction_AuditEntry]
GO





create procedure [dbo].cs_system_ModerationAction_AuditEntry
(
	@ModerationAction int,
	@ModeratorID int,
	@PostID int = null,
	@UserID int = null,
	@SectionID int = null,
	@SettingsID int,
	@Notes nvarchar(1024) = null
)
AS
SET Transaction Isolation Level Read UNCOMMITTED
BEGIN
	INSERT INTO
		cs_ModerationAudit
		(
			ModerationAction,
			PostID,
			UserID,
			SectionID,
			ModeratorID,
			Notes,
			SettingsID
		)
	VALUES
		(
			@ModerationAction,
			@PostID,
			@UserID,
			@SectionID,
			@ModeratorID,
			@Notes,
			@SettingsID
		)

	UPDATE
		cs_ModerationAction
	SET
		TotalActions = TotalActions + 1
	WHERE
		ModerationAction = @ModerationAction and SettingsID = @SettingsID

		
END





GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_system_ModerationAction_AuditEntry] to public
go
/***********************************************
* Sproc: cs_system_ResetForumStatistics
* File Date: 11/29/2006 10:07:30 AM
***********************************************/
Print 'Creating...cs_system_ResetForumStatistics'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_system_ResetForumStatistics]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_system_ResetForumStatistics]
GO




CREATE      procedure [dbo].cs_system_ResetForumStatistics
(
	@SectionID int = 0
)
AS
SET Transaction Isolation Level Read UNCOMMITTED
DECLARE @AutoDelete bit
DECLARE @AutoDeleteThreshold int
DECLARE @ThreadID int
DECLARE @PostID int

IF @SectionID = 0
BEGIN
	-- Reset the statistics on all of the forums.

	DECLARE ForumCount_Cursor CURSOR FOR
		SELECT SectionID FROM cs_Sections

	OPEN ForumCount_Cursor
	FETCH NEXT FROM ForumCount_Cursor INTO @SectionID

	WHILE @@FETCH_STATUS = 0
	BEGIN
		EXEC cs_system_ResetForumStatistics @SectionID
		FETCH NEXT FROM ForumCount_Cursor INTO @SectionID
	END

	CLOSE ForumCount_Cursor
	DEALLOCATE ForumCount_Cursor
	
END
ELSE BEGIN

	DECLARE @SettingsID int

	Select @SettingsID = SettingsID FROM cs_Sections where SectionID = @SectionID
    
	-- Finally, perform any auto-delete
	SELECT 
		@AutoDelete = EnableAutoDelete, 
		@AutoDeleteThreshold = AutoDeleteThreshold 
	FROM 
		cs_Sections
	WHERE
		SectionID = @SectionID
	
	-- Do we need to cleanup the forum?
	IF @AutoDelete = 1
	BEGIN

		DECLARE @ThreadIDToDelete int

		DECLARE ThreadDelete_Cursor CURSOR FOR
			SELECT ThreadID FROM cs_Threads WHERE ThreadDate < DateAdd(dd, -@AutoDeleteThreshold, GetDate()) AND LastViewedDate < DateAdd(dd, -@AutoDeleteThreshold, GetDate()) AND StickyDate < DateAdd(dd, -@AutoDeleteThreshold, GetDate()) AND SectionID = @SectionID	

		OPEN ThreadDelete_Cursor
		FETCH NEXT FROM ThreadDelete_Cursor INTO @ThreadIDToDelete
	
		WHILE @@FETCH_STATUS = 0
		BEGIN
			-- delete corresponding posts first
			DELETE cs_Posts WHERE ThreadID = @ThreadIDToDelete
			DELETE cs_Threads WHERE ThreadID = @ThreadIDToDelete
			FETCH NEXT FROM ThreadDelete_Cursor INTO @ThreadIDToDelete
		END
	
		CLOSE ThreadDelete_Cursor
		DEALLOCATE ThreadDelete_Cursor

		exec sp_recompile 'cs_Threads'
		exec sp_recompile 'cs_Posts'
		exec sp_recompile 'cs_SearchBarrel'
	END

	-- Select the most recent post from the forum.
	SELECT TOP 1
		@ThreadID = ThreadID,
		@PostID = PostID
	FROM 
		cs_Posts
	WHERE 
		SectionID = @SectionID AND
		IsApproved = 1
	ORDER BY
		PostID DESC
   
	-- If the thread is null, reset the forum statistics.
	IF @ThreadID IS NULL
		UPDATE
			cs_Sections
		SET
			TotalThreads = 0,
			TotalPosts = (SELECT COUNT(PostID) FROM cs_Posts WHERE SectionID = @SectionID),
			MostRecentPostID = 0,
			MostRecentThreadID = 0,
			MostRecentPostDate = '1/01/1797',
			MostRecentPostAuthorID = 0,
			MostRecentPostSubject = '',
			MostRecentPostAuthor = ''
		WHERE
			SectionID = @SectionID
	ELSE
		EXEC cs_system_UpdateForum @SectionID, @ThreadID, @PostID, @SettingsID

END


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_system_ResetForumStatistics] to public
go
/***********************************************
* Sproc: cs_system_ResetThreadStatistics
* File Date: 11/29/2006 10:07:31 AM
***********************************************/
Print 'Creating...cs_system_ResetThreadStatistics'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_system_ResetThreadStatistics]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_system_ResetThreadStatistics]
GO


CREATE PROCEDURE [dbo].cs_system_ResetThreadStatistics
(
	@ThreadID int
)
AS
SET Transaction Isolation Level Read UNCOMMITTED
DECLARE @PostID int
DECLARE @UserID int
DECLARE @PostDate datetime
DECLARE @PostAuthor varchar(64)
DECLARE @Subject varchar(256)
DECLARE @SettingsID int
DECLARE @StickyDate datetime
DECLARE @IsSticky bit

-- Select the most recent post in the thread.
SELECT TOP 1
	@PostID = PostID,
	@UserID = UserID,
	@PostDate = PostDate,
	@PostAuthor = PostAuthor,
	@SettingsID = SettingsID
FROM
	cs_Posts
WHERE
	ThreadID = @ThreadID
	AND IsApproved = 1
ORDER BY
	PostID DESC

-- Get sticky date for the thread we need top update
SELECT @StickyDate = StickyDate, @IsSticky = IsSticky FROM cs_Threads WHERE ThreadID = @ThreadID AND SettingsID = @SettingsID

IF @StickyDate < @PostDate
	-- Sticky is expired
	SET @StickyDate = @PostDate

IF @IsSticky = 0 AND @StickyDate > @PostDate
	-- A replying post in this thread has just been deleted
	SET @StickyDate = @PostDate

-- Update the thread.	
UPDATE 
	cs_Threads
SET
	TotalReplies = (SELECT COUNT(PostID) FROM cs_Posts WHERE ThreadID = @ThreadID AND IsApproved = 1 AND PostLevel > 1 AND SettingsID = @SettingsID),
	MostRecentPostAuthorID = @UserID,
	MostRecentPostAuthor = @PostAuthor,	
	MostRecentPostID = @PostID,
	ThreadDate = @PostDate,
	StickyDate = @StickyDate
WHERE
	ThreadID = @ThreadID AND
  SettingsID = @SettingsID

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_system_ResetThreadStatistics] to public
go
/***********************************************
* Sproc: cs_system_SampleDownload
* File Date: 11/29/2006 10:07:30 AM
***********************************************/
Print 'Creating...cs_system_SampleDownload'


if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_system_SampleDownload]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_system_SampleDownload]
GO

Create Proc [dbo].cs_system_SampleDownload
(
	@SettingsID int,
	@Username nvarchar(256)
)
as

Declare @UserID int
Select @UserID = cs_UserID FROM cs_vw_Users_FullUser where UserName = @Username and SettingsID = @SettingsID


declare @GroupID int
exec cs_Group_CreateUpdateDelete @GroupID = @GroupID output, @Name = N'Sample Downloads', @Action = 0, @ApplicationType = 6, @SettingsID = @SettingsID


declare @SectionID int


exec cs_Section_CreateUpdateDelete @SectionID = @SectionID output, @Name = N'Sample', @Description = N'', @ParentID = 0, @GroupID = @GroupID, @IsModerated = 0, @DisplayPostsOlderThan = 7, @IsActive = 1, @EnablePostStatistics = 1, @EnableAutoDelete = 0, @EnableAnonymousPosting = 0, @AutoDeleteThreshold = 90, @SortOrder = 0, @ApplicationType = 6, @ApplicationKey = N'sample_files', @PropertyNames = N'EnableExternalLinks:S:0:4:EnableDisclaimer:S:4:5:', @PropertyValues = N'TrueFalse', @SettingsID = @SettingsID, @UserID = @UserID


declare @CategoryID int
exec dbo.cs_PostCategory_CreateUpdateDelete @SectionID = @SectionID, @Name = N'Downloads', @IsEnabled = 1, @ParentID = 0, @Description = N'Files to download', @SettingsID = @SettingsID,  @CategoryID = @CategoryID output


declare @PicPostID int
declare @PicThreadID int
declare @PostStickyDate DateTime
set @PostStickyDate = CONVERT(DATETIME, '19791209 12:38:01', 112)
exec dbo.cs_Post_CreateUpdate @SectionID = @SectionID, @ParentID = 0, @AllowDuplicatePosts = 1, @DuplicateIntervalInMinutes = 0, @Subject = N'The Latest Community Server Licensing Guide', @IsLocked = 0, @PostType = 1, @EmoticonID = 0, @PostAuthor = @Username, @UserID = @UserID, @Body = N'This guide provides an overview of licensing for Community Server', @IsApproved = 1, @FormattedBody = N'This guide provides an overview of licensing for Community Server ', @UserHostAddress = N'000.000.000.000', @IsSticky = 0, @StickyDate = @PostStickyDate, @SettingsID = @SettingsID, @PropertyNames = N'ImageSize:S:0:6:', @PropertyValues = N'243742', @ApplicationPostType = 2, @PostID = @PicPostID output, @ThreadID = @PicThreadID output


exec dbo.cs_PostAttachment_Add @PostID = @PicPostID, @UserID = @UserID, @SectionID = @SectionID, @Filename = N'http://communityserver.org/r.ashx?D', @Content = 0x, @ContentType = N'application/pdf', @ContentSize = 243742, @SettingsID = @SettingsID, @FriendlyFileName = 'The Latest Community Server Licensing Guide', @IsRemote = 1, @Width= 425, @Height=283

exec dbo.cs_Posts_UpdatePostsInCategories @SectionID = @SectionID, @PostID = @PicPostID, @CategoryList = N'<Categories><Category>Downloads</Category></Categories>', @SettingsID = @SettingsID
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_system_SampleDownload] to public
go

/***********************************************
* Sproc: cs_system_SampleForum
* File Date: 11/29/2006 10:07:31 AM
***********************************************/
Print 'Creating...cs_system_SampleForum'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO


if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_system_SampleForum]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_system_SampleForum]
GO

Create Proc [dbo].cs_system_SampleForum
(
	@SettingsID int,
	@Username nvarchar(256)
)
as

Declare @UserID int
Select @UserID = cs_UserID FROM cs_vw_Users_FullUser where UserName = @Username and SettingsID = @SettingsID

declare @GroupID int
exec dbo.cs_Group_CreateUpdateDelete @GroupID = @GroupID output, @Name = N'Sample Forums', @Action = 0, @ApplicationType = 0, @SettingsID = @SettingsID


declare @SectionID int
exec dbo.cs_Section_CreateUpdateDelete @SectionID = @SectionID output, @ForumType=0, @IsActive = 1, @ParentID = 0, @GroupID = @GroupID, @Name = N'Sample Forum', @ApplicationKey = N'sample_forum', @Description = N'', @IsModerated = 0, @DisplayPostsOlderThan = 7, @EnablePostStatistics = 1, @EnableAutoDelete = 0, @EnableAnonymousPosting = 0, @AutoDeleteThreshold = 90, @SortOrder = 0, @ApplicationType = 0, @PropertyNames = N'SectionOwners:S:0:5:', @PropertyValues = N'admin', @SettingsID = @SettingsID, @UserID = @UserID



declare @CategoryID int
exec dbo.cs_PostCategory_CreateUpdateDelete @SectionID = @SectionID, @Name = N'Sample Forum Posts', @IsEnabled = 1, @ParentID = 0, @Description = N'This category is for forum posts', @CategoryID = @CategoryID output, @SettingsID = @SettingsID



declare @ForumPostID int
declare @ForumThreadID int
declare @PostStickyDate DateTime
set @PostStickyDate = CONVERT(DATETIME, '17530101 12:00:00', 112)

exec dbo.cs_Post_CreateUpdate @SectionID = @SectionID, @ParentID = 0, @AllowDuplicatePosts = 1, @DuplicateIntervalInMinutes = 0, @Subject = N'Sample Forum Post', @IsLocked = 0, @PostType = 0, @EmoticonID = 0, @PostAuthor = @Username, @UserID = @UserID, @Body = N'
		<p>sample forum post content</p>
', @IsApproved = 1, @FormattedBody = N'
		<p>sample forum post content</p>
', @UserHostAddress = N'127.0.0.1', @IsSticky = 0, @StickyDate = @PostStickyDate, @SettingsID = @SettingsID, @PropertyNames = N'', @PropertyValues = N'', @ApplicationPostType = 0, @PostID = @ForumPostID output, @ThreadID = @ForumThreadID output

exec dbo.cs_Posts_UpdatePostsInCategories @SectionID = @SectionID, @PostID = @ForumPostID, @CategoryList = N'<Categories><Category>Sample Forum Posts</Category></Categories>', @SettingsID = @SettingsID

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_system_SampleForum] to public
go

/***********************************************
* Sproc: cs_system_SampleGallery
* File Date: 11/29/2006 10:07:33 AM
***********************************************/
Print 'Creating...cs_system_SampleGallery'


if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_system_SampleGallery]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_system_SampleGallery]
GO

Create Proc [dbo].cs_system_SampleGallery
(
	@SettingsID int,
	@Username nvarchar(256)
)
as

Declare @UserID int
Select @UserID = cs_UserID FROM cs_vw_Users_FullUser where UserName = @Username and SettingsID = @SettingsID


declare @GroupID int
exec cs_Group_CreateUpdateDelete @GroupID = @GroupID output, @Name = N'Sample Photo Galleries', @Action = 0, @ApplicationType = 2, @SettingsID = @SettingsID


declare @SectionID int


exec cs_Section_CreateUpdateDelete @SectionID = @SectionID output, @Name = N'Sample', @Description = N'', @ParentID = 0, @GroupID = @GroupID, @IsModerated = 0, @DisplayPostsOlderThan = 7, @IsActive = 1, @EnablePostStatistics = 1, @EnableAutoDelete = 0, @EnableAnonymousPosting = 0, @AutoDeleteThreshold = 90, @SortOrder = 0, @ApplicationType = 2, @ApplicationKey = N'sample', @PropertyNames = N'SectionOwners:S:0:5:', @PropertyValues = N'admin', @SettingsID = @SettingsID, @UserID = @UserID


declare @CategoryID int
exec dbo.cs_PostCategory_CreateUpdateDelete @SectionID = @SectionID, @Name = N'Wildlife', @IsEnabled = 1, @ParentID = 0, @Description = N'Interesting Wildlife Pictures', @SettingsID = @SettingsID,  @CategoryID = @CategoryID output


declare @PicPostID int
declare @PicThreadID int
declare @PostStickyDate DateTime
set @PostStickyDate = CONVERT(DATETIME, '19791209 12:38:01', 112)
exec dbo.cs_Post_CreateUpdate @SectionID = @SectionID, @ParentID = 0, @AllowDuplicatePosts = 1, @DuplicateIntervalInMinutes = 0, @Subject = N'Ready for the chase', @IsLocked = 0, @PostType = 0, @EmoticonID = 0, @PostAuthor = @Username, @UserID = @UserID, @Body = N'A picture from my backyard!', @IsApproved = 1, @FormattedBody = N'A picture from my backyard!', @UserHostAddress = N'000.000.000.000', @IsSticky = 0, @StickyDate = @PostStickyDate, @SettingsID = @SettingsID, @PropertyNames = N'ContentType:S:0:11:Width:S:11:3:Height:S:14:3:EXIF-DateTime:S:17:22:EXIF-Model:S:39:13:EXIF-ExposureTime:S:52:5:EXIF-FocalLength:S:57:1:EXIF-ApertureValue:S:58:5:EXIF-ISOSpeedRatings:S:63:3:EXIF-Flash:S:66:1:', @PropertyValues = N'image/pjpeg42528307/15/2004 09:08:18 AMCanon EOS 10D1/5008f/4.54000', @ApplicationPostType = 64, @PostID = @PicPostID output, @ThreadID = @PicThreadID output


exec dbo.cs_PostAttachment_Add @PostID = @PicPostID, @UserID = @UserID, @SectionID = @SectionID, @Filename = N'Cheetah.jpg', @Content = 0x, @ContentType = N'image/pjpeg', @ContentSize = 20558, @SettingsID = @SettingsID, @FriendlyFileName = 'Cheetah', @IsRemote = 0, @Width= 425, @Height=283


declare @ptr varbinary(16)
select @ptr = textptr(Content) from cs_PostAttachments where PostID = @PicPostID
writetext cs_PostAttachments.Content @ptr 0xFFD8FFE000104A46494600010101006000600000FFDB0043000A07070807060A0808080B0A0A0B0E18100E0D0D0E1D15161118231F2524221F2221262B372F26293429212230413134393B3E3E3E252E4449433C48373D3E3BFFDB0043010A0B0B0E0D0E1C10101C3B2822283B3B3B3B3B3B3B3B3B3B3B3B3B3B3B3B3B3B3B3B3B3B3B3B3B3B3B3B3B3B3B3B3B3B3B3B3B3B3B3B3B3B3B3B3B3B3B3B3B3BFFC0001108011B01A903012200021101031101FFC4001F0000010501010101010100000000000000000102030405060708090A0BFFC400B5100002010303020403050504040000017D01020300041105122131410613516107227114328191A1082342B1C11552D1F02433627282090A161718191A25262728292A3435363738393A434445464748494A535455565758595A636465666768696A737475767778797A838485868788898A92939495969798999AA2A3A4A5A6A7A8A9AAB2B3B4B5B6B7B8B9BAC2C3C4C5C6C7C8C9CAD2D3D4D5D6D7D8D9DAE1E2E3E4E5E6E7E8E9EAF1F2F3F4F5F6F7F8F9FAFFC4001F0100030101010101010101010000000000000102030405060708090A0BFFC400B51100020102040403040705040400010277000102031104052131061241510761711322328108144291A1B1C109233352F0156272D10A162434E125F11718191A262728292A35363738393A434445464748494A535455565758595A636465666768696A737475767778797A82838485868788898A92939495969798999AA2A3A4A5A6A7A8A9AAB2B3B4B5B6B7B8B9BAC2C3C4C5C6C7C8C9CAD2D3D4D5D6D7D8D9DAE2E3E4E5E6E7E8E9EAF2F3F4F5F6F7F8F9FAFFDA000C03010002110311003F004B8B99C5D4A3CE7C6E3DE9BF6AB9ED33FE74970BFE9728FF006CD285C0E6B8DB676217ED7723FE5ABFE749F6DB9CFF00AD7FCE9AD8C5474AE3273777247333FE74E5BAB81D666FCEAB0393CD498E28B8C9FED938FF0096CFF9D385ECFF00F3D9FF003AA258EEA9109340685B37971FF3D5BF3A05DDC7FCF56FCEA14426A658F03A52B85C5FB5CFFF003D5FF3A517971FF3D5BF3A3C9EE4E3EB51C811472C07B6695C2E3CDF4FFF003D9BF3A4FB64F8FF005AFF009D57F977AA96E5FEED38005DE3CE193EF0F4A682E8985F4FFF003D5BF3A4FB74FF00F3D5BF3AAD9575DC8E197D41A41D69816C5EDC631E6B7E741BB9FF00E7AB0FC6A01C504D20B8F6BAB8FF009EAFF9D1F6BB8CFF00AE7FCEA2269BCD0172C7DBA75FF96CFF009D20D427FF009ECDF9D5570D8351856EB40AE69AEA13633E6B7E741D426FF9EADF9D5019C52856A18D32D9D427FF009ECDF9D27DBEE319F35BF3AAFE5B5288C9145C073EA5720E04CDF9D4916A3727ACCFF9D57F209352A438A2E2B1686A1381FEB5BF3A6B5FDC7FCF56FCEA1D98A77979145CAB01BEB8FF009ECDF9D345FDC7FCF67FCE830FB537C9A04585BEB8C7FAD6FCE8377704FF00AE6FCEA25402A655145C7A0AB71704FF00AD7FCEA4FB4CE07FAD6FCE9B800534914AE2124BDB81D256FCEA237F718FF5ADF9D122E6AB3290D4EE1727FB7DCFFCF66FCE946A1703FE5B3FE750247BBB548B013CE28B8128BCB93CF9AFF9D48B7571FF003D5BF3A62454F2B8E052E60D053797007FAE6FCE9AB7B705BFD6B7E74D65CD204028B81696F27C7FAD6FCE97EDB3F4F35BF3AADD05358FBD1711685F4FD3CD6FCE9EB7931FF96ADF9D671622A546A622E9BA9BFE7AB7E74C3773FF00CF56FCEA02DEF4D66EF48562C7DB26FF009EADF9D1F6E9BFE7AB7E7541DCD315CE4D3B08D2FB6CD9FF005AD527DAA6FF009E8FF9D662B9A9F79F7A5A8C5B880FDAE4E3F88D31A220568DC20FB449F5A8B62D17119FE4B114D301F4AD2F2D693CA18CE28B8CCE5871D453CA7CB570C40F41479591D28B819FE4E4D4C9055910E3B54CB1E2936088A283DAA45504B11F713EF363A7D3D6A53F2A31CE0E29D0451CF3AC7193E5C69BCE3B9FFF005D2B9455BAB70B1B3E36F19099C331F7F4A883DA45E5B790D1B919619CE0D477B7B1DB5E2CF7D26C817EE2BF01DBFF00AD50CDA85ADFB6F8654057F891B22AD26D5C86D6C589226289B2633232F4200DB9EF59175680B2BDB12202791C839EE735A49394007504751CF14EDF146980CA559B028032EDE467731088F9217F7732BE33ED56ED5DA766492331C80FDD3FE3DEA593CBB3632100C6072CBFC39FE951DC4CD736BB0E1ED98F0D080A78F7EA285A85EC58488CAC523F9D87040E48A1ED9D1F6BA9523AE6B0E7BB5B2555B390479E91C673CFA93EB5D369D65245669F6872F2B7CCC4F6CF6A725640A572AFD9CFA53C5B13DAB48420538443D2B3E62CCD3699ED4C6B4E7A569B28151601345C0A22DB1DAA45B51E956C20A7EC145C0A4D0F3D293C9CF4AB9B0134F58C53B81485BD2F93ED57BCB03A8A6BA80295C65231E29314E9DF1558CDCD315CB1B41A0C63151A49922A7520D02B9098F9A4C1AB41334BE48F4A2E32A9069369AB9E48F4A72C00F6A57114BCB38E69A60C9E95A1E501DA9A545171D8AB1DB815298C014EDC052839A570222B8A61426ADECCD208FD68B8153CB348C8455CF2C67A535A3E29DC0A0739A420F7AB661148621E99A7715994B6927A715284C54E21E7A53FCAA1B02BE29AC0E2AC98E9A62A00A6D193DA916322AE7943A6297CBF6A7711504673D2A6D952797CF4A9760A10C75CBFFA4C9FEF5301E29D703FD264FF0078D37B0A091437BD286E314D00934ED8715230079A7645370690A9A0078229EA7351A21A982714AE3109C2E7BF6AB96532D9D896942F993B6D00FA55472B12177E481C6074AA734CF79613C3190D360ED1EF8E94D0333F5CD1E6F165EBBB5C082D6D8ED5C2E416EFC54B61A1DA69200871E6852C65917E773E98E9B7DAB57C3FF67BBD2208A165478C7CCA4FF10EB9A9A6025BA11A43212876B15E4127A13ED5B393D8C925BB30E0B88AE6768E68DD2771B954A1E7E9FE1526A32C11DAB8DBB7611963C6D26B62F6C45DD8B890180720163B5D587753D8564DFC534BA56D943306501896C82474CD4752EF632AEAF1FECB0D9F9626F90EF23A03EF4AF7CB6DA004689A3B8E9823827B7357B4AB4B87592E5A18D58C580B27453DF07BE4564EB48EB6AACCDB892576A7407B1AD23D887DCC25BC58A759A60AD939603A035D8787BC430DCA7D9666C49BF6A1C641F627D6B897B3721951F1205E98A6A493C1286B79024831E681DEB49414958CD49A67AC9E3AF5A4CE2B92D23C52162FB348FF00682831BDCE181F43EB5BF06AD673461BCE553D083D8D72CA0E2744649965C934D0A73528018641041E8452118A82C6E714D32629587150B034D12C955C77E6A55718C5545CD4EB4D81396E2A37E452F3DE984F3486549E32D5585B9CD699506916314EE2B14D206039A99626156B60A508052B8EC4488453C714EE290AD0000F34F1D29AA94E230290C6B3544D4F63CD37AD3022DBCD488B8A5228CE28024E298CD834D2C71D6A17639A2C22532544F3E0F5A8598E2A060C4D3B08B3E764F5A915B3556343DEA6070281960114E38AAEAE01EB4FF338E690126050454624A5F307AD0018E696985FDE9035311260645495086F7A9375301275FF0049933FDE34E58C114976765CC9F5A885C6053B129968201485455749CB1AB0BC8A96AC340A8334A53A53C0A0E6A4A1AA805388CA900E38EBE940069CA3340CE0753BCF10D9EB11D88492E269DB6C5E92F3C62BB4D174AD4B4FD395750319BC662CE01CEDCF6FC2AEA0DAF1ED821795640D1BC9FF002CFD70696EB584B36297967343C7124637AE7D78E6BA749C7439DBE591CD69D0B69BE229A0967321B897785553803D6BA89EE21B62248D1B08C718E3FF00D75C45FCA6FF0058FB458BCA3B1F317A9F61DAAD5C6A17916D82E1D815E7630C83F85572AD0573A1FB53EABE641736ACD6814E597827DB155EFDA3B2B0B58F4AB78FCB2E17CA99492C0F5FC6AF787354B8BB85DE795088C60285C607D2B4354BC10D9B7D99E1F3FAAA3AF39FC687105238AD4B584B0D424B3895E442818EF1CC471D3D0D66DD0374F0430179377CCCD8FBCDFF00D6A7EA32DE4D697536AB6E04ED2E102F157F47D359FF007F67BD51970CA5BE550053B585729CF612D8333451EE95D4281226467BF355AEAC1F528D8A5AC505C20C3CBC843FE35D558C52DDDCB98D800BC15403F0CD41757B78D24315C59ADBDB08F2F22F196CF03D8D2721A47032691398A578E32FB3EF3C6739F7A79D46E20B2160969E517018C849DCD5DF47A15B456F7296F3AC535C166C13C938F4AC96B275B9D3E3D4A1799F67EEE68B8C30E403ED494D3DC391A652D275AB9B5890C4E6E6DD066484F0E83E95D169FAC5AEA8B9872AC3AA37515492E85CE937B34FA18468C907CA3B4BFAFBE4565694B676F6C751B4B898A8936BEE5E63CF66F6F7A96948B4DC4EBF34D65CD66D8EB315DC8F14988A543C863C1FA1AD45248E958B4D1AA698D588D4A131DA9C01C52D48C8DBA544C79A9586693671CD00460E29C0E29DE5F34852801C1B22919B8A02538AF1400D534FDC314CC628340C9378C534B668099A5298A04466907029F8CD0578A06309A073415A3914C4230A8D93BD4B8CD05734015F60CF4A0443D2A5294BB714C56212A14544CD9E952CBE955FBD218A09A1988E29E178A42BDE9A1323DC4501C8EF4EDA4D288F9E698840C4D38350168DB4C63C354B9A8953A54FB2900DD401372FF5AAC2227D6B4EF221F6973EF4C48FB53E622C528E32AD57632318A71807A50062A5BB9490FC8A51CD300A701EB523B0E23DA941A5C0C530F1486480E6A2B8B686E71E702D8E9CD26F229324F4E6A93684E37122B7B7B7FF00551283EB8AABAA69C2F503A01E6AF73DC55E553DEA40BC6285269DC4E2AD631BC3A234D44C3705917B81EA056AEA7F658E62ED724246809279CD52BEB168AE16EE3241CFCF8F4ADAB7D2A39674B891D5931928791822BAD49495CE769A671B71A75D6B6AEB6AE02BB111EE1D7DEA7F0FD85DD8E992DB5D4A762E77056FCB1FE15D07F68DADC199910ADBD8F0EFB36EDF5C7AFF00F5EA9594F6DAADBC973653BB47E76CF2B1939EC2A5B1D89BC3F1DAD8EFD32CC4FF006B98198978F231EED4FBBD392082D6D6F237B93773124AB7C91F5600FB0C56E69DA14F0EA897C7517F22384C5F66D831B88E4E6A2D3B4D9748B1921BE9967DD34D229EBF29E8BCD66CB4735068309D71759FED1FB4460958D14E5471D33F5AAA0CD61A95CC56F7AF2DDDD46D34113608561D31FCAB4EDFC32B1D85DDA58486179E43CB1E109F4F4A5B1D16DF4CB0B2B9D71D5AEF4F62C2656E8B9E33EB8A49976337FB5B5CFF00845B75C58ECBC8E65E3CBC17527920550F12EA16364458B426096ED01678B0021FEBCD6CEAFACC1A84A6C34FBA5370F133C6DD9811D8FAD7257963756BA3B3EBB0B3CB137991316CB01DC1AB8ABEE44B45A115A4976FA7B2B448F25B9F9E2DBFEB17D41ED5A961A95EDA9665B29E4818823AB6C1ED9E7EA2B134ABCBA5D52DD22CBC53A95DA47E22BA4D32D359BED21835C2DA5CC539F2B7FCA244F43F8D5C888BEC69E9FA98BA9A6B7995619A22303770E0F422AFE6B9FD42582EF595D3A7856DAF7CA1E5DC20CFCD8E98EE2AE471EAB0A5B4C1E1B987708E648987C87D413FC8D6328763553EE689EB4A0E05453CD25BB48CD06618C64C9B80C66A18F54825F30A248EB1805D82F0B9FAD438B2F991681E6A5500D508356B09D8A24E03838DAC4024FD2AD47796ECE515F0CBD430231F9D2B31A64CCB8E6A23C9A955D1C655D4FD0E69850D2023239A518A711E94D02802452076A46346D23AD00734002A934A452E405A6EECD00308A319ED4ADD68E940098E69702928A00080298C69DDAA376C503229066A3F2F9CD5802976F14C442179A714CD3F6F34EEF4AE043E5F3D29760A908A653019B4669703A77A701DE91863DA980A179A9B150A9E952D005AB9C19DFA75A6A802993CBFBF71EF5189093C54816490453703B0A62E7D69D400B8C503AE690364E29E05200269A69F8C8A631C1A00615A923419A66E1F5A9236C1A604A22C738A7AA734DDF4E0D8A9024F2D48E4022A0B789EDA695DA6262C0C03FC233CD48D3851513CA240475AB849C59328DD1A97D3DBC166FBA2477927198801863D87E1C5642697FD946DE3B2844925C3B3B246DC29FEF1FC4D4967F679F463792879A5C6D254E36919E4FD2B3D627B6D224787516BAB89976AB31C84C11C7E24D7433246DE91A76B565E2A9E69E7DDA51B5023C1CFCFDF3EF9CD52D7351B2BFD560B94BEDB1596E478C3705CFAD5A8B5DD660B3D0E292C7CD92E9D92EDD7958C038CFE350DEF82AC66935068E5922FB7105C0E42B039C8A8D06881BC3DA8DB586AFF0062BEDF35EB07872794FC7D69977359C3A5DA69DE2360B7573008E420F7CF5C8FC2B56C7518A6BFBCD1B6BC725842A44C7B8F5C555F12785ED7C496704CB74239E3C05941CA91DF8F5A4B7D4A7B6873DAB691A27877ECB7BE5CA059F47CE59C9F5AC1F13EB10DF5C8B28D99ADA787CD47AECB51B2B2BDB71A75F453C88A014B84E84A8C726B82D767B44464B5447368BE5AE3A85CD690D5EA44B4467E99A8DC581FB4C30798219401C7F0D761AF5ADD697796FAB4B3BC96B7057621FE0047439E95CE784AE648FC411C1B40814055DC39CF515E85A6EB169AE7DA525B261E4BEC7327CC8ECBD0E3B554F4628EC67DFDC5B5A59C1ACDEDB896488EC56C618E7A5525B4B5D28CDAAB5D6FD3AED77BDB9072324115634DBA6F10CBA9E8DA95B8F2636CC781B70A0F407B71D2ACC7158DED9DC68B2C7B628F312173827B8FD0D47A8CCBD61EFE2BCB6D4B47CDCD84D105F29017403B823DEADDD4769A7DBADA245756D15C480B490364C0C40C707F879E956F4DB68B49D320D3ED2F55A71CA993B8CF3C7B5646A9A95FD978B6D51B7B5B4EA14A81C367AFF4A7ABD0362D148A38A19AEAEAC9DED5CC7348611B4E4FCA7D55AA88FB55DEB318D4EC8E2605567809F2A5F4C81C63DEAEC1E18963D56FE792747D3AE410F191F31CF3F811EB53DBC4FA1E8D8B79CCF6D14BBC9938D8BDC7E54AE90EC63D84516976BA949736D2A796E7947DD191EAA3B5225DCE218EF21D5A31607FD6090ED68CF7031DEA5B5D266875A7BF8E78E4D2650CD23337CA54FF00091FD6AC0D074A78E6D3614664BB3E629F301DB81C15A7A06A2C77D732DBBCBA65C0D4230D83E6385703DB8C1A6EA5A86A563046C823FDFA82124902C919F4F435560D3A0BBD16E34AB59E4B736F316679C6DCFB53A3D1D7FE11C957565FB4CD01324262972FB3FC2959751DD962DE5BDD39609269A7996E47CD1CBB4F967B65876F7A74371AFCFA8086E6116B6DD4CB1ED6C0EDD7A8AA31AE9FAFF87440CCD67F6020192425B19F5AB2962D3F84E2B317C27677C477119CAC7CE4293D40A2C82E3EE754D5A4BD6B3B0B6864741F32C8E1587BFA114F9F5B6D28DB7F6A6E1F685E152304A1F720E0D4165A7AE97A5B45ADC890C924A5609B3BB008EB9A7E91A56A50C57967A8471DDD8842F0B487702FDB69EBCD2696C1764B2789F4D8EEC5A99773671951C67F1AD5DEA76FCC016FBA0F7AC5B5D034BF12DA1B895FCABB5E2E05B9CE08ED8A92FADECDEC6D9ECF54FB29887943ED190AF8E30C3B7D454B8C7A14A4CD7071C1EB4A791596A93E9125BADFEA3198EE07CA24CB007D9FB8FAD5E4BB8BCCF2653E54BD831C071EAA7BD438B452921E4F34C3DCD121C37355CCDCE39A928B008A5CF3D6ABAB1A76F38A62262C01A073510249A900E0D0038E3150B362869874A88B67BD003D6434F23350F43D69E1F9E6801C3AD4DC5434FCD301D38FF487FF007A9B1E41E6A7953371267FBD4CD98352C0941E3A519ED8A44523AD0D48072AE4E69F8E688D491D2A464E69300032306A0950E6AC27030695D45032AA46714EC106ACAA80314C6033CD17019D0734BBF148C7B522A96E31400C6259A9C8BC75ED4FF2B1D29C0639F4A6232BE1D6BE93CD79A25DC610F9CC6267E777FB3FD6BAE974CB7B70B25AC0224072598632704671FAD71BA0E985FC72B085CF92C67638EABDBF535DF788343FEDED3C5B35C496C3A931B727DABADABA39AF6763060D6EE743D2AE2496D1A7B787CBF2E4439DCA4E0E7D0827357351D3751BBF13E99A8DBDDF97A7C11B1962CFDF27B7BFFF005AAED9DAE99A0DAC3A4B48844A71B25392E4FD6A86ADAA5CD9CFA7ADADBF9B14B78217E3F87D6B26FA16B7B9655A19FCD6312C734A0C6DB800C4678F7C563697A5CBE1EF0F5D5A6A1A8C4A1E6668E41CEC07A67345F68D7F3F8DE1BFFB428B582321533C9CFAD64F8A7EC32BAE8B7972C82E3EE92DC29ED537D6C6965B94346B2D7ED6E6EE5BEB8335A3A315C3E55BD08AE52EACE3B0967B82FE7C6D28E50F519AEFB510346F0DF96672C90461496EFC631F957156C2CF4DB3B71342675B99B72397C0073C1FC2B683329A2ADC5D49A76AA8E90831899081E8BC57A444B6DA5585D4B688DB9D8CEEB9C83C76FD2BCEEF524373249B331B920499E33E95ABE0CBBD404D3C378E5EDD863E639C7A62AE6AE898BD4DBD17C42DABE937372D01B77B76C4AC98C9152A4BA3EAB6536A96B23E123F9B2C46C2BEA3E9489A86996D7A74D5F2ADCDD0CB2328058F4EB55ED74DD3B46B6D42D0CAE6DE6CF99BF82148F5ACF42CCCFEC9BCB8F1069DA869D379F68A54F9D9F957D456EEABAFD9E9DA9C66E1049B9C246DB47CA08193F9D45A6FD920D0123D3AE269E18119B2B8F9BD4566D8C3A6F8CADB6BA4D6F716980AA8776F04F4E68DF70D8B307F6C0F1A651E4362E85B27EE320071F8E6AB6857B73A95EEAD697D215B6DA49575FB849C7E1C5696BDADC3A1CF6B67B2691F685600E3E5CE07D4F1D2A2F105CC3A2AA4D25A37FA592594800C800EFF009D3F90BE64763A70B7D22E348B9BC8E7B39A5C452236D600F5FC8D36EFC297B6DAA59DE5B5C20B588A06677DA500EBFA510F87E1D5F473FD9F388CDE49E7C4921E17FD8CFA56BBE8B8F09DAE8BA8DD3FDA9D98E51B704C7F0FBF14376028789740B8D6E6CE9D3A2C609055DB19EE08F5ED4ED4AEE2D13C3F0A6164962511B11C2F99D48AA3AF59EB5A6EA56C34B4B86B745023F2F90A475DD5A3A9BC72AC5A7DDD92CC6584CB72108FDDB7AFFF005E8B6C3BEE2E9F796DAFE90D7935B4690CE3CBB95C60EE519C822B3BC3FF00D99341A9E9BA7B4A1E6C9025382A3A641A668FABD815FECEB02D6A9139902B8CF99EBF8D627F695B689E2476B189F2FF002B876CE33C9C53484D9BF616571696171A7EBF189EDA3917C87E186EE9C7A54BE0FBB9AF46A96F7437C1038284F38E7A0AC2D527D604505B1919E2925323927B13F2D687886FEEB42B4D3AD6CC04927F9DE58C63CD6E98349ABE8099A9A578753C297977AC5FDDA7D989202827241E9F8D3F58D2ECFC470C131BB4B667C9819F80C0F3820D696BF79611E81036B303219B69921EA738E9587E21D2A6D76CEC6F34184DC59247B046A798C8EC6A2376EECB764AC6869DE1B58342FECCD5DD2E72E4C6AA7A71C6D35CFA59FF0068596CD3276B97B262B25BDD9032B9E307F4CD743A847A969BE0B8B7922F60886E2BC95F7FA8AC9F0D8B7BFB0BABF8D648F506530CC54E5598F3B80EC6AD5C9D0944B3E9D716D63731B08A75FDCBBB6E653DD18F7F6AB70C6B28F31082B9C7D0FA565F871DF52B0BCD3F5572522702391F860F9E304F4356B77F67DD4921694318F2E5871291DCFBFD2A651BEC352B6E5C75DBC52A2669967731EA36B1DD43F72419FA7B55B5502B17A3B1A8C550292404A1C538800D3881B68B8EC679439A76D38AB455476A4DA09A7726C4489DE97CB3926A70A29AC79E9487618074A931F4A6E7DA9D9F6345C0B131C5CBFD680477A75D28172FEB9A62F1480954645214E693CD03BD44D3F3D6901723031CD296CD411C9BBBD59500AD4811E48ED4E1D326860334D60476A63240411D6A3939A4DFB4542663BA9012AAF7A78E075A623E69C7819A603B7629C0AFE350673CD1B8834C0D5D0ADE04D60DD08B370F188F70ECB9E6B5AF2FE4B6D4E18595C24A386ED9F4AC4D1A461A944036DDD919FC2BA10D2BC29F688D4CA879C1E338EB5D14F58984F491535DB1B1895F5C9AD1AE2E2CE22D1AAF24E391815486A73DCE950EBE917FA20B43249005F9C367B7E19ADF8EE524455C81214DC50F24561B6BADA8C1736BA4419BBB6915648244DA0A6EC363B74AA6884D99FA958DC6AB3695A86997EB12A389083FF2D2323A7D6B3FC43E078B5AF10437CB7450643491819C81E957FC596F713D9CD69A2AECBEB129208938250FA54F66B26A7A769F7F74935A5D21CC8A38CF623E9DEA2CD1A5D3323C5F626FA18F4E455093295F97AA9C75AE2EE34BB4B5892DF02ED6D93CC5883FCCC475C7B57416965ABC7E38B9B9BADED68A8F96278C1E80562EAF1ADA6BE358809102A32AC67839C73571BAD09656D434A0967717826005E32491C3DD147F5AA5A26B8D63AE881E3730CBF21206707B1FA53AFF005BBFBED1A17D84A481B7B6CFB9CE00CD526B98ECD50C9F78E0647AFAD68B54475D0EAB59D092F7518756694948C8F3554761DC54F7CA2FAC2EA396E522B795C057738E318CD658BDD7EF22B71A7299202764802E793D8FD6B6F56F0FD9EA02CECEEEF12D2E429550C782DE959BD19A2D4B3A1E976FE1CB78ECFCF374647243A0E1B8C8FC2ABC9E20D1ECB5AB9D22CE116D2DC101AEA2007EF38E2B4E1D31747D092D62B86BAB88236D8EE3AB76AC8F0FDBC7ABDDDC4FABF87D22BAB4019A7C101893C67DFDE9770EC4B7D6B677EE8DAF44512CF28B71BB0255CF43EF5767D3B4EF10DB18EE4BB59DBA0104E9203818E99EB9E39CD45ABD81F12E98F691DC4093ACA194AB64601E722A2F0DD8368D66F65713C724F21690C6877051D3F5A57D370EA4767FD85AD4B069D6134B6E2C1BCC503237AF703F1A83C49A16A77779FDA96374924510070250AC8DDF1F4A93C39A5D95B6A77B7D6BF682F1B14F2654C1427A8E6B1D3C4B7336B3269F3DAC714577218E5403919E3356B7D04F63A8BFD697FB152FA1BBDCD101E6188F0CDE86B9FD0B5F4D535D7796D104AD1ED2E0E495F4AD15B6B2D1F4BBA8A183302124027717247FFAEB95B2D7AD2D6198C1A7C76AA23DA65C92C4E7A7D688A5606DDCB7E22B9D3347D452EAD2029713820AA9E179EB8AA57EF0C3622F4DA896F09E243CED1EA455799E3BDF2AE268D58E3E42C3902A6D12D75FD5F5178ACE3FDC0CAB17C040BE955D056D6C58FED5B89EC21BCB9CB36CD8703A2D767E0ED574FF001487B7BBB08DE6B101E26917705F7ACCD3A0D3F4F8B568EFA286E6C6381564C365C3F7503B63D6B47C03ABF87A79EE34ED1ACE4B492552EFE69C99074E0FB565269A7645A4D136AB7DE1CF165E49A0CD76D15D893E495470580E40A967FB37827C31245A7B34ED1B0DE58F3BCF73E82B3AFF004BF0E784DEE3C416DBEF6EA29309117056273EB8AD3F0A6B56DE30D2EFBEDBA6AA942166DA32B2FA7E22A7A7915D7CCA9A0EB9FF000915ACFE7C2C6EED54BED46C0954F6C557B6D3523B49E2D190DADDDD7CDB246FB847518EDDEB5E48742F08E9926A16D6D2C693615DB92DF4E7A572F269DABA78CACF59B1579ECA791641283C053D41156ACDE846BD4B7AFDB1D5B4B5B5D3AE639F50B33FBF8E2E093DCFD6B3B5DB7D4ADBC37673CB231B8894ADC2F7DA7A13F4E2B7E5F0FC3A7F88E6D5AD2E59257472F1638763D08AE56DFC49773E87A9B6A4A267B77017230DF376FA5545F625A26F0FDF3DAD8EF88A4D1AB0F362CE1933DC7A8AEA8B64641041EE2BCBA19923BC33C25918C7B401DF8AEDFC2F7E750D12367CF9B09F2DF3D7D8FE5535A1D5174A5D0D81ED4E66A8F2474A0E4D739B067340A1412715288F02810DA5D99A0F14A5F140C615C1A9368A68352D0017320172FCF7AAEF2FA1A7DC2937327D69B1C059B34088FE76E681192466AF08297CA0BD45201B04640A98B10314A9B547BD1919A5601F10C9C9A74D8519A6070B514B364E3D6818D6248C5445315281918EB4EF2C6280238F83D3A54ADCFF00853400BD29AEF8E94C43C7140E6A2CB11D2A48C7140C961644957CCCEC3C363D0F06B66C6EA4F23ECDA8005E16D89321FBEBD89F7F5AC16E98AA179AB4FA56B50482E91ADE78BF7B6CE795238DCBF5AD693E86551753B749ADD26F3BCC019B081FB91EF50E9BE22B3BEF115DE990C615EDD465F6FDF3F5AE326F10DB5C27EEE5F941CEC6E952784F55B08B57733B6C9A51B52527F435BDAC62F53B3D41F478B5BB53732AC77F3218A2C923CC51CE0FAF3546E2EAFAE6C2E97ECED6D77133A46AFD1F03E520FA1AB5A868F65A94311D5512736EE1E3941DA50F6E959FE32D3754D52CA293489C9B8B5932555B1BBFFD551BEE52D0E55B50F1341E0E92EA4B226F5AE7660A7257D715CC6B773A8CF70AF7615608A2236018CB1EB9AF41F195F5DE9DE1933042D3A001C0FE162393F4CD79B6A135CEA36B6324A1802A5A76ED9E9550091A87518A5F07D9DBEDF2E275628578DEC0F71ED5CB5F486378B31799CE7A64576BE20F0C496DA569CD6E36456B0950879DE4F25AB8A8EF50CFE5EE0029E86B489123ABF0DEBCFA3BBA24619AE542A6EECDDAB46DA2FED011DE788225B7BAB590B2956C71DB35C837DE1872B9E50FA1AE87C3367A95E437125DCC93C5293190CD90D9EDCD4CA3D4A8B7B136AFFDBF75AEC171A50F3ACF2A4286C023B835D27F6823DCB5A3DCC693C9C4B016C15503B562BDE59F82EC3CB7B59D52472323E655FA7B54777A5699AD4B0EB918613300CBB1F6EFC7AFE559DAE5DCA3A56916F6BAFCB769A84A0C2CDBA3DBDC9E01F6ABDA8C925C59CD36864A5D79815C85DACD81CE09EDDE99AA5BA6A7A2CD269972BE79C066539248FE1F514FF0D5B4ADA1BC17D94BA248DE5B2C06287DC097C34755B5B6B86D69CAC23E742CE0B835026A316A1ABED55D3DDC370E9CC88A3F99AAB2DFC3A45A3D9EADA9477B34E580F2C72063039AE744367620DDD9472BC918E0B1E41FA55257D5937B685FD6B56BFB7D51E3B58B1112183B0CE47AFB564DE5C4176DB5D17CC1CC687804FA9A9E0BABAB9479EF46DDCDF2A5269569A73DE4D777123315273FE02AD2B225B26D2B45BBD4176DDCCB146C7064270A9ED9AB16FA0F89B48BB32E8A64BCB657F95E16DCADEC7D2B7A2D76C5F446862B485648F263594E79FEF1F7C5667873C7F71A64E967736710B432658C430464F24FAD47BCCB491D47887CED2B4C8AE2DF444B99EFCA4776107723A63F3E692C2C345F075D5B3D9D8DD4D7B7E044D86DE20CF5CFA63356974EF13B6BF760DDA49A65D40ED6F28E3CA623E5F7CD63F82BC35E26D2FC4928D409162C87CE76937093D08FC6B1E96341963E23F0F68BA95C68A6092EA0B9B826E26940237938031E82BB89EDC69F6F3C1A7D8A5BC4B179A8D128019BD3158CDE09F0BC97726B731282197CC70B3031E47AFA64F38ACEF196A3ACAEB76375A4CD23DA48AA63687E64624F20D3493B584D983A16AD737FAEC9A7EA05EE2DEE03096193900E2BA0BEF13D968F716FA76C65C80802F488638FAD2DF4B6906A45608218AEE66392060B1C76FC6B1BC41E1F92FF0057B5BFF316357DBE72F52AC39E3D6B5D1B33D51575ED4F52D1A7B30F70670D2962DEA33F7693C47A85ADC0934F28A924986700609EF9A65CEB3677B25C9D460C4769304898752DFE358372D1C9AE4F2990BB483F76A7F8463BD546226CA7716AF145FBB3B9D09DA47B9AE8BC237D22EA11DA30052788EE23B38E4572CD24C6458D49C1EA7D4D59F0FCF3E9DABDBB9070D305627F235725789317667A981CF34F001EBD69BB81191F853D4015C07607CAA687930BD29C064D32451480891893CD05B9E68DB814C3D69812E40C53F7D5739CD49834EC05E9A1FF004873EF4E8931C62ACCC83CF6E3BD34145A421A463DAA1724D3DE55CE01A6F0690119908A40D9EF448B9A45434008D21CE3269C13710694444B722A60981400D45C53E4E1698C767348599E90C89893C0A9228B3D45288C0EB5229C0A6215A35518C649A66DDBC0EB43B9FCE91549E4D00237033597ADE8316B96AA864F2A68CE63900FD3E95AB202062A3DDB0534ECC1ABA3CD4D94FA6CCF6E67732038C49DAA9B4DAA59DCF9D1B160873802BD4B5CB04D4BC372CF0420DE4238651C8C7F3AE7B4AD0A5D5A2F2EE6292DAEC8CC41930B20F635D5195CE792B09A66BD77AD5FA4297B2C42F22093AEEDB823A32FBD74DE19D3B5DB0D7D436A26F6C5A3227278C11D38FAF7AE0757D32F34298CB3C1246AADF2C883806BABD23C4F2DF6A76CB607EE400C8F23E031F7F5A25DC11BB6DAF5A6A973A8D9CAA21B8B7C8314BD197D79AE3E4D1163D46783507C7DB58082257FBA00CD761AB68D67AD595C4823482F2EA22BE60EB91DAB05BC33A85D5FE9922CF86B04D92CAC7E5276F51509AE8534C4B9B6BB1A6E99A55FCD3ADF349298642720AE30326B88D5B429B47BA5691159F682CEBC827BD7AA5969DAAE95A65B24D7105E8B689B72B2E59989C8DADE9DAB989AFEE758D3AF24BED1D6D7C83FBB720FCE73C8AB84B526513936756843050430FA54FE1FD5EFF49D4CC3B8B59CA72C1BA8FA53264565C2AE727241ED5504ACC8CBE5074E9835A3641E8375ABDB5DDBBBA5BADFDB91B8AB10369F707A1A8EC7EC9710086CE02AC32160DC3E507D08EB5C7DB153A7C8A1845205386CE33C74A934AB8FB15C43756CAA1A3E7AF2DEB50D157365B4EB3F0CD95DDDA6F47738397CE7F0A3444B5D7ED0DF5CDD5CDABDBB6DD918E09C77AC4D4F5BB8D62ECC5343B6DD9836D3C73ED57AD6FC5B3B410B6D8D06164039DC7B9F7A2DA05C8EE6C3487B98A173FBD57DDB3764E05645E5E476B726255666E3E503F214F9ADD7FB464D46591D9D9F7649EF4FB694DDCACE23C67AB1154262DC324701791497917181D6A258BCAB40628F000C9007435AD6D606691B729C2E39FAD6F69BA6C71BCD1C8A19186304544A762A306CF3595B32105BE63CF5A96CE6FB3DCA48E8264539643FC42BA5D7FC170C664BEB176DA3968FD3DC572B1ABC20F9BC80783551775740D35B9EAFAFF886E753F05DC5D68B04F02DBF961655EE9DC0FA74AB51ADCDEF836CEE353BD92D350BD83C853C80493F2E47AE05723E09D6350B26BBB4B13F68964881B7B57E5598B0C9FCB26BD0F5EBFB8823BA10DB334B6D6E26572015CF4E07A8AC24ACEC6B177D4C1F05F83F54D11AFC6AC6396D278CA1843EE594E7AD66DEF8BE2D2F525D1E1B6586D54840A0E027F9356BC3FE2CB9D520BA8F5027168865564E3AF041AE3B5A96C35ABC5D6206655270D111CB115A28EBA99B6ADA03B5EDF78D2DE48CB7C8E18B11C28EF5B7AB6AB60B2DE6A36970F2470308CC6D9C17F51ED4EF0342D7D1DC493ED432031ECCFCEABEB59F736DA6585D4DE1B7DF3EF3E63CDD0061D07E554ECDD89D52296A53A6B3636B26C481CC9E63AA8FBE7A565DED9BDADD194362594648FEE28EB5A17B6CD6DA95BDC2C67EC91A647A13D2A2D46432DC5C4F2A2C7F26085E95A220CC5B98A001986E6278A963D49A0D462528080C0E4F5150D9C10CEC0B0CECE6A4796CE4BF527EF46739EDC550753D4D3E600F6233520E9C715142E1A1461D194107F0A716C579CF73B16C3B269DF85301CD05801D68011B00544BCB63152B11B6A2F330714013845029F81ED55C3963525319A972F899FEB54A590E0E2A69A40D72FCF7A8CAE4D2EA24411AB13939AB2063AD28C01DA94D016236CE7A54B08F5A40BDCD024087A52604EC001CD40EE41C66832163EB404DC4645002A2EFEA3352B288C6694958C75A8DE5DE693003CD1481B02903E7B53024118C6E2280C3A0A55C94E78A444C1A008DC126ABC8AC2AD48C01E2A195895E053432DE87205BD1131F9645209AEA6DA382289004076F0A7AD79FDE79E9A6DD49036D956262A7D0E2A6F87FACEA93685733DE2992181C6C62793EB5A416973299D56BF691DEE9ED6CD0ABABF18615C0DCF87ED749D6AC0C23CB590B0F2C9F415A4DF1210DDB09ADCB44188C8F4F5A5D427B6D5D60D420908DAEAE99E323D2B56A442B187E2FD5350D26F74D92CD5BCA660ECDD99BA107F0AEB2E626D4BC35702194412DF4612189CE08FF003CD58B0B782F619A1B8896448D77A8619C1AE4B5F7BA9FC6FA65B5BA388E008508CE07726A23AAB16D5990EA175E28D175D86D6DF7DCDB45128643CA74EE7D4536F2EF50BDD605828558028790B1C924F615AD3DFEBED713A8B544864B9DB1B30E481FC5EF5574E82DC5FCB235F25CDC44C4320EAA6AD3D2E46EEC675DE8A50EE418C75C77AAD7BA608A24F2D472BD7DEBAC6607B553B858D9769031DBDAA154EE68E08E02EAD276316CC8CBE2B716DA03029863236AE064756EF5A371620AA9400953903D68166554AAF4C938AD14CCF94E7F52B38E6B9135A8658F030ADD8E2ADD85917B7DC5396E735B915927945597EF0EB8A9EDED9514051C0A4EA0D40C49B4BDA42901948CD3EC74FDB26CD9D715B72C59238E9524508421B8CD4BA9A14A1A90416AA92487B1C55C44C608EB4C6C83C548A78AC5BB9A243F6F1C8E0D79FF0089B4C8B4EBF23A5BCDF3267B67A8AEFB39AC2F16E9ABA968AEA4ED9613BD1BF98ABA6ECC99ABA39CD1649B4AD406A56B92F676F2381F5181FCEBB1F03F89AF3554BC1AABEF78177A4807507820FB560F8100FF008486D6D2641379D1BC6C87A38DBCD775ADE8F6767A64BA7E956C96CD70A54327049ED93E95ACED73285EDA1873CB646DAE2EACAD5238A5C891A21C3639E7D3BD737A2699A66BF7255647B6168FE67903A38AEABC29E12D4B4AD2EFA1D4954477585080E7A7F1565DB7858787AFAE2F56E4C8A2260AA17900FAD35A09DCA3E1B96EA0F1B5CAC7685E14DDB901C0C76356EF74AB2D4EFEF2785D45DC836940DFEAF3DCFBD5AD0F5C81EF6E74DB689E396580BC5237077E338AC0D0E1D42C61D4B50955A09083B4BF5639F4A684C982DB053A60944AD1811AF3919F5ACEF13DAA59A46899F9C7CE4F7355B46D2AFA6D5E1B90F85C9777EA01EB8AD7F156E7851668C028721B3C37D286ED2490D2F75B39682786DE3C31C17E300734DFEC969246D9201BFA67D6ACC5610961330DC7A81D6A8CDA8CCB72CA87186C0ADAC66B73D5EDC14B7863CF291A8FD2A51D2A0833F65889EA5067F2A7678AF3DEE76126FA4DD51A9F7E29770ED45807B1E3151A8CB669A5CF4A7230EB401280179A7EF1ED55A4971C0A6F98D4D2034C8C4F213EB4A5891E9514F21FB538C719A93A28F5349A0444662ADD78A9D25DC0554954EEC815661FF5583D68604A64EC2A19037DEE691721F26A6665231DE90C8A2DDBF9E2A7326DEF50918E477A6EEDD9A403A498B0A6C72FA9A69C28E453181C64500591203DE9EAC38A86242C3FAD4FB303AD004CAE314C91CE302A1DE43601E28660050028CB7269E5902E2A1DD9185A110F7A6226F2D5E3653CAB0C11EB5D2E9B656B63A62476F0AAC6CA0E3B7E35CB99368C2D6F27997DE1E16D6D3AC771B319F4E7BD5C08994AEFC15A26A12FDA668A48CB0E91B616B95F11C17B66D05BD88FF475701881CA806BD034DD3EE2C6CE1B67B9694E09DC78EB5CAF8A088AF0C4B90FB94641FBC0D6C8CF42AEA5ADDCE8966B75005705D5640C3AAD7508F632D9C334613CC316F1C82CAA466B9D8F4B83592B6172CCB1CBFC4BD411C8AA575A2EA567E345684486C45B840DFC380318ACA36668F7087C576BAAEA2DA68122B26E547EC48ACAF0FD87F67DDDC0725E5964662DD80F4FAD6EE97E0EB7D12E65BE595AE257525548C05CD65595E5CB6B66D5E11E5A96DD28E9BBD056BA59D88D6EAE6C952133507945CF3560B1236D382E3A0CD72DCDCAC20DA4FE94EF2C28C9EB569403D692440C703A53B85883CB523DA9000838C539C6DC5279648CD17018C724E39A6862BD6A558E99328518C53010382735206AACA3BD4A9D79E68608796C726A9DF079AD678C7DE68D82FE556659369DA69AAA0B6E3D075A2F6158E4BE1EC530F1769C672774733819EFF2915AF77AEEA767E3B852F0388D6721A16E9B4F19159F6B791E8BE30B66738314E1C0F553FF00EBAEFADB5CF0CF887588564543790922212AF2C7D8F7AE97DCE7443A9F8E34CB6BE16FE638646C13DAB9865D474DD427D5AEEF8CFA6BEE755CE4F3D2A4F16F826F8EA725FE9D0B4F0CA7E6451F321FA7A54B73E1DD427F04C1A6BBF9572A0B1563D7D01A4924377D4769777A6CF0A6B71DB0373B5937004E3F0AC6D7B50679487624B8F99474AA9F6D9BC336367A6019B99A50D29EC149C1C536CDE1BED6E5562CE8AEC403E83A0FCEAAD6D457BE86F68B095D3E360BB19B93919E2B33C5E812DA27772486E9DBF2AE8A365400602FB0ED58DE29804B62AF8070DC9F6AC212BCEE6D25689C28D55B3B238F81D33576C6D2DEE668E778F0CC4641F5CD361B08626670BCD44D7B226A10431A9FBEA081F5AEC7B1CAAC7A731DAB8EC062A1DD91D69F292471DC5351091CD709D823360E29CA460934D65C1A5514009253549A57E0D00F1E945842633527962A319DD53E0D3197E740B7121C739A66EDC714EB862F70F8E80D323520D4808EDB4F34E4605A993290D93D2A304AB022802F1002E4F355F782F4E32EE8FAF4AAE8DF3E690161896181D29CAA02FBD3632075FCA93CCDD263A503126E281CA714B2F22A246C363A5202C44702A472587CA7AD547723A1A449C8FBD4EC2B96C2E054520C77CD46D7191C1A8848CC7934580B516075A92470178A815F2BD6A390B2E4E6801FE6FE555157594F12D9DE69C2478385902FDD033CE7F0A371DDD6B7FC39A8C3626E45C36D8767985CF41570766292D0D5F11EBEBA34100F2BCD67E335E6BAEDF5FDDF8AEC8BC6C91BB024649FCEBD5AE62B3D534A8E56449E3FBCA719AE27554DD7A8CAA308F8C7A56E6112C69F218EFADD864E241C7AD5DB4D5EEAE2D2F1B56845979770523DDC6E5AC88A7F29C498FB8777E5CD5CF1D5ADE6B7E1F8A4B45DD9219A3CF3CD611B6C6F2EE4BE28D6E0D0F4D6B825A40EBB6209D18FD6B96F0EDDB5DE9EB706355334CC4B13CF1D80AB769E1E92F7C2EB06AA644DBCA275651ED59FA3ABC1796D6C1592DE0898827A124D6A92517632DDAB9BA0B938AB018A2735189141A909590006B9CDC5561B734824241E29B9E703A54AA107140C61009CB52AB29046295943743C5342AAF7A40294039278A827C1E94E7939C66A07932719A6205C0A95003935031F978152C271D7F3A0431E3DD28152CAAA88117B7534A0756F5E0546E79C1F5A37199775E1B875CF10E9AECC530C5642BDD4722BA45F87365FF09045A95BDD3431A3890C1B72723D0FA565473C905CAC9192AC8720D75D63A83DDB24CA77EC8DB7281CE71915BC64ED6319456E56F11EA5A96917305C5BDA7DA2CDDB6CEA99DEB9E847B573FE33BAD5174BDFA4A132B919DA3E60A7DAABD97C42BB9F5BFB2DDC20DBCB2145206190F6AC0F1478D6FA2D664B6B360B1C4DB4E57AFAD528BB89BD0A7A85BB4E6D2FAE9F75CAAEC789BB11EB4EF0EC512EA592A4B1CD50BED50BDEADBBA7CD2FEF0B7D454D6774DA7CF0CDC7CAC338EE3DEB56B468CD3D6E76124789001599E232E34E09D8B0C9ADB01655595070DCD50D7E3DFA35CF1C84C8FAD71C5DA48E996B13CEA7D57CB9FCB550C8BDC5686936D6F73A8DADEB0272E3E5F7A80E910328E369C64E2A3B6BCFB0EA7690AFFAB8E51BBDF9AEE7B1C8B73D2CF2D8229CCBB578EF502B9F32AC9E40AE03B0AC47E74063DEA42B9A8CA9040A68047E4640A6648353851B6A1908DC075A602A9391EF53EE3512292054FE51A00BCFF2CF2679E6AAC92ED734B7D7405DB22F0DBB0055267D92344CD928C4134F949B96CCE4F2D4C69411C556966F976A8CD337E46052B0AE5B866DF95279A5313AE4C646E3D3355506C3B8F1F5AB8932B28E475A1A1A64864C1DB8A215CC99E69400C4538E23E952325902FAD529A455231449739279E2B3E7BC40C0672685106CB3E764F2682E59B0BDEA88919DB2338AB506E53BBD7B569626E4E54AE33DA98256DD814E9252C40C54F045104F326CECEC3FBC6B365828611993071D8FAD31A724728F8FEF638A917CC9C832B770005E028F41524F18CA90781C6053405640ADF5AB3630C5A8DF5C69523855B8B46048EDCF07F3A8176877518254E322A2B179ACB5D4B9811A490B6D0BD778E334D1327A1AF6F35CF83FC39069FA87EF1E498E086E02F6AAB25CC2F04E8E76CE6E03286EA462BB0D5F4ED3F5B88DADCB0324643ED56F993FC2B87D434C686F4DDA02D189FCA6DDCED00715BEE8C56E4CAAA71BBA1EB5D97910AC5941952A09C76E2B8D8B03E66E47A7A9A8F563AEDB43632D83CD2ACF31762833B40E315CF146F266E4DAA585FDEDC59C1711F9B1290C9939AE6349B896F6D668E5B758D2D1CC6AC3F8CE7AD6AFF60C3A6EB377AE79CC0CB1167887F09C73CD66E97389F475991195657246E3D72735B69CAEC67F695C9C617A9CD588C861924557555625378DC064AD30B053B54D739B9659B9C0A68665EA7AD31582F6A6BC85FA5004924BB17767B7150ACAEFD4D3CC794E4D33684EF40870049E681174C8CD2EE555CD33CFC9EE69812850A3A73498DC703BD2AF2B934AA7827D781480459803B474C71485807C91907B5392DCB3F03F2AB8968AA37BF6A2E0C852D9245C9FCAA392E2E34BBDB5BFB4627C89079D101FEB223C37E23AD4B34A73B23181EB42A15C31EDCD35269DC4D26AC69FFC21DA1CDA88D6614625DFCD5546FDD9F7C572FE2AF0BE9F36A6752DAC8E486745C0538AEB34EBEB2D2743559E7090A3B0CB9FBB93902B9ED7751B5BED3E5B8B2BBF3540209419E95BA6DBB98BD158E12EAD60935E7B99DD846A8701464F4E2A33BB62EFC1CA8FC699A637F6E5EC714B98C33EDCAFA54B3A8B597C876E13E507D715BF5323B3D06EE6BCD391A6B7316DF95493C381DC54FA94664B394019F94F158BE14B972D35B99F200DCA8DFD2BA465F535C725CB33AA3AC4F3D91840C7CCF971D41A5D33438F53617B1BAB01F3E01E4107BD43E24B4965D51E08F3F78B1F7A74D6F77A169C8137466E231B883CE0F6AEDBDD23936676D8CAAB01D4034FDD9181587E17D41EF34AF2E5626585B69CF523B56D0207D6B8A4ACDA3AE2EEAE4CAA314C913737142313CD05F71E2A46348217039A8027CF93539CE3A7148AA4F38A06390E31536F3512900E054DB680294704B2EAF9C642C9BB9F41CD462DE467F30820B1DC73EF5A370592F02C6482EE7247A639A91A278C8326133D17B9FC3D2ADC999A45216DC0CF5C53447E5B12467DEAE4831C8EB55F6EF383C0142020652EDC9A51161F2ADC77A1C7273903A66A48A12CC3E6C01DA988B28C4228C7D4D4970C3C9057193C0A8642E19500E7D29AA08910B1CA82011ED51B97D0CF72E09EE6A0FB2B3CBB88E95AC12397E6421B9C714A22038C7E155CC4D8A4B188D40EF52A6172506E3DF1534B179673C6F3D07F747F8D3EDA28D83173B517A81D58FA0FF1A4D8D223895844679106D07001E84D356669A5DC7A76C74FC29D7923390A400A06001D00F4A8171132BF63C1A5D07D4B85CF017A8A00660416C0F5AADE6E1B39E94C6B97DDB472CDD0761EF4582E26FF00B34B32BB80A0EEDC4F7EF496B3471788ADB51777296A0B00ADC37E15626B657B759597CCF307CCC573F30E2A9E99008F555694E2024292E30073CFE1568991D8B45A545E25FEDB5BFF002E4BA8C23216CA9CFAFA554F114C61778609374724818B0E83FC6B6E1FB149613DB9B588C56EEC8898C838E86BCE7C40974B791DA42E5C9F9CAE71B39E84F7157177336AC6C33852AAA3712428507D6BA0D1EF6770F03C5B2DE08F87230189F435CE2E58DBA060BB7059739278E9ED5B37906A579A0486CF6B4910C4117F78F727E9DAB24B535E845E20BE86DB41BCBB489E7C2105954ED3DBAFA573BA22492F8621292F9403FD703D0574DAB6AB1E9BE1BB1B5D671F68B94F2DD00CE4F4358F6DA4B59E89C3283E69DAA0F55ED5AC7E168CDFC4848D52342A8092C7939C963F5A640BBE53F36003CB7F41503C85731EEFF788FE429AF2951B538CFA565636B97A59533B579350331CE4715073E5E7351B33FDD069D8572E89CB1DA289236C039EBE94CB68BBE39AB7B0938278A9634450C45873CE2ACA42A73C74A7C71EC153A440AE6A5B1951909CE3A0A589324123F0356484499107F16735349147D47D734AE3162511AEE239F5A566F3060F4AAE252EFB33C0A9246F2C0148042AA9D853586E5A373483D29E02A0E69814AF34B8B57B1974F99CC69311871FC2C3A1AC7B0F025E686D72D7176B2C3226008F383EE4574523294217B83D3B54FAEEBB6DA6D9E9D65A8AB4735EC432F8CA83EF5B5393B18D448F304823F0DEA703A2EFDF23804F63DBF9D4DAFE9724FE1D17C80F9D1CA44807E86B43C51A7DB4D71F6C8670E9032A90A73B588EF59DAB5C5DE9D6F114B86922BA1F3C6474F4AE8BEA636D0CED0EF25B3686E812190E0E7B8EF5E8C2612C6B229F95C64579CBA8DBE8185751E16BF692D0D8CAE5CC3FEAD8F5DBEFF4ACEB474B9A529741DABD92A5EDB5F0191BC2C9EE2B675D363A9ADB593226F6607E8B4E92D92E6068DFEEB0FCAB2AFB4A96E4ACF14844A8B8C93CEE03FAD2A52BE815236625BD843A6C225870220E632C7A9E78AB5BC115CA7887549E5B586D9418A34FBC01EA6B53C357735F69A7CFF99A26DBBFD476CD1523757084ADA1B7B82A54424039A6BB8C6335113938AC5235B9604DBB814E572A2A28A03F7B352961F9500387273536FF00A552694E401C0A7EF6F5A761DCD2954ADF17E922E78F4CF7F7A9265F306F39663DF3D6A3BE3B6F26047F1F5EF914915C71B64E9D9BD6864A62001B04B71DEA30815896276F7C0CD3A3766DE8F8DC1F031DF3D0D472CE0482307E5519FA9A5A8F41A51E46DFE5970A085507BF6FC6A481845321111938DD8CE0539266895CEDC853923F0E323F3A8AF6468278AE147EE54E1F1C8048EBFCA9EA22662132CE0177E49AAF3799E5318946E0095F73E9523CC938C81C7D69D97124688AA5194E7D411CD2B587B8B03AB46AC100CAE4014292ADE698CED56C6739EB4F01622F146C0A9F98363AFAE3F1A5B8665B778C0DA2301F9EE690215E0DE8D231E4FE66AAAB47092642A09E82A492EF7C1138C64A8CE055695E063BDD54B766228482E45732E5F18A6167906C0B43DBDC3A79A15922CE379E33F4A43388A3F313843D58F5AD12E84B137A93C8E7038F7F4A7C6815B2482C7AD44EBFBB5921287BB65BE6E7D07A53AD5C25CA24F1B49B94B00A7973FD29D985CBD0CAEA76348C17A1E7001F5A9741B48DE5DF2C6AD1B39606E0E79CFA7F21D28135A65E1F3028C7CC26F94863D7F0A92E6748B4F125B22F9F13EF59073BB8ED4ACEE2B9B971A94561F6A54E598EFCB2E17A0E79EBF8571FFDA105FDE3DFA90D13100B9E369F5C7F5AA3AADD5EEBCAD7259C1DE06C63F28C7FF5EAC4124BF60649A24456F9311F39ABE54912A4DB3434E6011E6380653903BE2B4567D4E0D1A793468C5C5D34C328DD1463AFE358113BA03F393D36FF00BBDABA1D2F571A3AA7DB7CAB7B59542A3BF56973CE4F603350D1A5C5D72D6DEFEC2D25D65512E908C82D858DBD3DCFB5645CEA16B6D722DA5721B7719EE4F4AD5D534CD36FAD592F3533772C6ED3C3B1B8FA1EC6B9996F122D45E0BA61BA4C147DBDF1D2AE3748896ACD130A30796460B1A0C903F9522C7118C1CE49E699E7B6C5561B70385CF35483181FCA07F76DCC673F74FF0077FC2A2C5DEC5B923E719E3B53A281DA4E450840C6482455F45C47B80EB498D6A224586C53E465040EF558DC1126DEE69F925F27F1A96868B68E460B0E054CD2A94C86FA554672540A8D0B34840E8054D864924DFBCC819278AB6013164F5354E2FDE49C0C81DEAD4CFB63EBD3D2900A8AA80B534C9B8F3D45461BE405A9AD3A8E71458091E5DA3815134E48EB41955D7007268822DBF3BF6ED40C50C767231C574BAF69FA76A9A2DB0BE8E370143445FA86C76AE62598EE38E456BEAFA7E9FA9F85609B508E567B787723444865FA015B5232A8B638AF13785068FA7BDF4174D22B48048A4631DC7F3AA5A1DDD9CDAA587DB2D662A8863632A8F2DC13D79F4E39AED5EE1750F09425B6CD6EF10762FD5C0E3F335CFE878BFD1DADA36123A5C7948A472AA4F1F5AD39B433B6A729E30B49749D7DD235FDD6ECF038C1E6A97F6A4BA55C453DB8CB039C7AFB1AEAFE25DDDB586BF04063DFFE8EA188F6EF5C8128D2038C86E456CB5465B33D2F4BD42DF53D2A3BD8BE40E30C87AA9EE2A42730CA0753C8FCAB1BC316CD0695BD94FEF5F70CF715B255C9DC3031DAB917BB2D0E9B7344C31E1737D2E2639849C96F435AF61A6C5A0E8F21678CA282DCF191568DDF936A70BC839C0AE6FC67ABF976AF6B193893B7A574277307A195A66BD25DEAC6DE50A23918F97ED5BF7B243A76D3752797BBEE9C75AE4FC2DA74979AAA15C601C82C719ABFE399A437915B2A93E5AE58839A1C131A9B46D35FAA4225DD98C8CE40CD569B5DB3822572CCFBC65428E58565DADC249A4E5CE760F722B9D5BE9609088CF53C9C6292A687ED19D958EAD1DF3ED29E536780C7935A7893DAB94D1EE95EE919C82C7B8E6BACF307BD44A3665295D134B72C6E245DE4FCEC0E79EFC5482602227866E9B47356AFF4A85E57F2372F3F31F734C8ECE3894A127D06D38E29F20B9D19CD249110C391CAE0FF004A5B7996E26F2E121589C6D3D56B41AC6D8A6155C28CE093934E92CEDD172D000C460B1E1B1D734F91F41F322B5D7FA2C8CF11DA3706E4F0E70304FE59A81E6DDC97639240FAFAD68325BB95761BF8C0DDC92054A9044C705554039008E953ECD873A39E59A4B162C4620DD80BE9CF515A3F6832469146AAE1B059F3C63AE335AD77A72982213471BAB293182436D1EE074AA012313158CC48233F2AC5D0123BFBD0E9B0E6192333CC8AA0B6D2381DFDA9D7B2ACB232B03E59C93EFDB3492DBDDC476C32AB903055C72A48EB91FE14C68B64331900462413B06463AFF4A4E9D95C6A45416FE5BC72A3395650AE57D7B1156E3DE2F0DB130C6C8011239FCFAD58B695A78C64AAA2AEE3818A64A226BE85C00EAAA47CDCF5EF54A0AC2E620D511D21493719406C12C7EF0F507B0A874F5B2F39D66DEEA70C8846133F8F5AB5AB2C935A1DA708A4670319AA376A0416D2DBC8A1DC15DA39C0C75A5A263D59A82DE13345346AAAF11CE1865587A30EE2B1AFEDF548EF0DE93E64A1F20A0DAB8EE00ED5B115BDD06880910F037B77C55A9010B903381CF1F7BE9FFD7ABE842DCE66696E9D58F93E6CC643BA32A373670723D455BD4351B5B7804F7513985390919C9FC874E7D6AE1096F04F012646BC2BB1D53E6419CF1E9591A8E9135E6A1712587EE664604824B06C8F5F5FF1A98AB952D0C7B7D7AC657746B968A363BB023F9947A1209CFE55135F5E3663B7D4ADE68B0CEA236DAE0E38C822B5A5D0671166F34886455193E480AE0FA8DBD68B1D1B4E0E162B3950A4A373C9D58118C0F4ABD1233D44B27D6AEECE3B92A91A6E557320054E39241F7ADCD6B50B4D62DD20BFB762F2315889C2C7093C0639EA7F95675EDC8496DAD20BBC67263810606338191E9D6A1D4035EDDD9C17480C45F322C671D3B7E27152E37D4BBD8B30D9DAAE98DA519CBAA9DDE606E491DB2471F8566FF633EACEF24577E4A07030C09E475E6AE9D56D1D3EC96A58146DA4118DB8CD5AB0D4607B33E5C00B9E42270587AD524EC26D5C7AE9532911ADCAC81001BA41F337BE4523E952B09037CCBC7DDE49FC3DAB075AF15CCD70F0E9E11178CCC392D59536BDAA4F1323DC91BC60941B49F6CFA51EC85CE7596B345F6F9ADAE2E621242AA15777FAC24F6F7F6ADD85D5D8425E30F9DA14B8C93E95E484B9C1272C0E735A3A7E937DA895F295979CF98C481D7B1A6E927D4155677DB51A477046158A93E847515304057792029E84F7AA169A1416B6881F373708397773CB67D338AB50C0ED190E37267186181F4C562E9BEE6AA64AE48181D4D3D144568D295FBC7007AD323996473195DADD718A999259F10A2FCA7A2AD4BA4FA0F9D082E2358F72F71E94EB55375BCF61FA51142BB4A1651D80CD5A816221BCB91778FBD8FF000ACDA68B4D32BCA02C646381C0AA130658F785CFCC179F738AD2DF186C3E4D66EBB73E4698D2C45576CB1FDEE9F785086F42E18445D3B75A1F2E9C1C5011A47C6EF7A19A08A4D8F2E5F19DAB523214819DC22839E95B83C411E9D62D1EA16D2594118F2A3965C7EF0E3AFB0AAD64B2BEEB8B789098864798700B7604D519B549A4B9FEC9F10406E0DE2E0BC70FEED7D81EBF8D6D4D194DF417CBB08F40736D771BC06362815F232724FD2B37C2BA15E6A1A333DACED663CD2CF201F3371D17E94DD6DECECE44B0D3ADD63408576AF43EBCD6B7853577B582D74F8E0731FDA0ADC480FCAA4F451FD6AF6237D4C2F17697793787ECAEB5368A7B8818C5E6AAE0BAE78DDEF5C5C56CD2CB1A2292EC70057ABF8DEE2D61D2E4D3E520798DFBB39FBA7AF35C278734FF003EF9E6979FB39C28CF56F5AD14AD1D4871BC8EA6DA3F2AD6289801B100C0A7312338CE29448E87A034D798BBEDDB5C7BEA74EC31A7655CFE958FAC68EBABC0D83B641CA67F956CB5B971BBA0F7A8D6DE493804802AE327125C5332B4648F46B5324B1825465863A7BD71BAFEA7FDA1AA35C2060B9C03E95E893C51AF0793D0D663E8DA54923B9800120F9D0743EFEC6B7554C5D3399B6BF10D815C80C47A63358ED0DC5CDC1F2A36249FE15E2BBA3A6DA8B7FB3BC2248BF877751F4A9ED6D23870A89D3A67A8A6EA82A660E93A6DE448AF3C5B31D3815B9FBDF5FD2AE346C08C8E29F8FF0067F4ACDCDB2D412343506796E648D9CBC4B212BE59C06E9F7BE9CD3C300A1A45C13DB351DD7093B8E0862011D851E5A10AE46580EB5BA312492508305405C727355E39629676023CA2000EF24727D29241B9F0DC8CD1F720240192EC7A77CD0344CD16DCE246FC00C53D18AC6BBB939E7B5471FCC109E495C9A589419704647BD0006E1D65DD90573C83903F4AAF1303279D9D8AEC5B6AFD7BD580A3E7E075C543028F2D38E840FD6931A11D9E596593CC6059BE560013C1FF0022A0941B6B3DAD23B85196673CEE27B56ACFCDC95ECB9007A553D6494B072BC10A1B8F5C8A97D8A8EE25A064B740D18727EF1CE00FA8A2647B5B69774EA1594B061C15F41CF3535B002D67038CB127F2AA33286B00A7905B9CF7E9537D2E35B94EE3509329048B239D982E4601E3AFA75AAC249247FB3F9726E570A5C8CEE3EA2AB5CB31B911963B51CED19E0735A86474960DAC4665A928DBB5DED17CECD96FBC586D0B51CB701E3922B79407007CDCE5B9E82AC5CA8DA8B8E36838F7AA3A6C6B25D5D338DC617FDDE7F87239AB93B2222847DBE52CAAD244D12168F60FE207BE7B558B5BF5921579E4C37F1285E09A98A8FB5C098F95E33B97B1ACDD3FE7BDB856E42EE503B000544772D8B6935E5C4F2B971E52B1F2B38FD4D4B2C2AC50CD2EE7553920633EF4FB289134988A285CAE4E3BD59BB8905947205C3210A0FA026B5B19DF530A5F0ADB8533A4D32396564914E5979E83FCF414EBCB60648E5E45C40C5899138998743C7E7C5748F0456D042615DA5F058E7249FC6AADEC31F9E89B015685D883C8DC0120FD73DE860737A768B6FAAEA3F6E258CA923199211B2327D0FB53756D0F4D53E6B858981C178C9C7E9E956EC608A488965E5D016C12371DC7AD692A25C493C32A2B46908DA31D320E69A7D44D7428D9F8574757564884BB46482DB973F4AA2DE12B0FB4BB992411B1CAC6981B47F747AD741A75A41069D12451EC5DA3A13CD4BF62B773B9A204A4B85CF614F99872942C6C2C2D90AC3611A1CED5665DC5BF1A73232BA95851631D0678FCA8B9768B505810E22DDB76F518C6714F9C95BC481788C6E50BE800E052BDC63C90CAC1573EB91D29D14933611153F33D2A4BA511A00A300AE4FB9C0AA6DF282178010F038A00B5285560D22EDDDC865A748F22C4648CEF6EA011546EC05B600700B0FE9576100DDC6879503A1FA53115D2F7CDC24D624264E651FC3EC6A687ECEE4BC337EF072093D053AE8058DC818C8E7F3A48006B76240C920671DA93498EE4B1DD41336C2AAADF5E2B0F546CDADB5A4E0490DCDCAABE4F2801CE3DC558B9458EE54A0C6EC06F7AB1A6D9DBDDFDA7ED112CBE48DF1EEFE13EA2B19534B545A9B7A32F174862E76A2A8E5DBD2B22DE585F5B771379C9220D98E466ACC31A5DE9B71E7AF9987DBCFA62B9AB376B50EB0B1401D94007A0A9505629CCF457BF7D3F45296F62F71383931AB0C9F73E82A859DDDC25A5D6B133CC619220A96F2807C97F63E95909753B0B72656CBC24B7B9A9CDC4D2E8D76B248CC3CF55C1F4C0AB44330E7D496F268E458C2C9CA36EE4139E4915D3F872282D674BC9640F6FB5E5B6CE55A5DA3990A8E3BF7AE53548D20B680C4A10B49B491E87835716E268A5D3D12570A8E22519E8849CAFD2A6F7653D8B1AD39D6F5C176E53C80BB95377CC7D4E29F1C2912178536091B7703155A751142CD18DA5E40A48F4DDD2B5955718C703A5151D90423A8C48DFE501B2CD52C88B12E7033DEA4B651BDB8A8E7E5C83D3358F535200EF3673F2A8E82A2CCD92412231FAD58451BF18E296E00385EDE94D099484E276F2821F7344B6830366463A8AD286089412A8053CA2F3C51CD60B192B6ECA774869F2010C7B80E4D5875067C11C7A524EAA480450B561B15222D2C83238CD5FFB32FA8A66D089F28028DCDEA68E603FFFD9

exec dbo.cs_Posts_UpdatePostsInCategories @SectionID = @SectionID, @PostID = @PicPostID, @CategoryList = N'<Categories><Category>Wildlife</Category></Categories>', @SettingsID = @SettingsID
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_system_SampleGallery] to public
go

/***********************************************
* Sproc: cs_system_SampleWeblog
* File Date: 11/29/2006 10:07:31 AM
***********************************************/
Print 'Creating...cs_system_SampleWeblog'

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_system_SampleWeblog]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_system_SampleWeblog]
GO

Create Proc [dbo].cs_system_SampleWeblog
(
	@SettingsID int,
	@Username nvarchar(256)
)
as

Declare @UserID int
Select @UserID = cs_UserID FROM cs_vw_Users_FullUser where UserName = @Username and SettingsID = @SettingsID

declare @GroupID int
exec dbo.cs_Group_CreateUpdateDelete @GroupID = @GroupID output, @Name = N'Sample Weblogs', @Action = 0, @ApplicationType = 1, @SettingsID = @SettingsID


declare @SectionID int
exec dbo.cs_Section_CreateUpdateDelete @SectionID = @SectionID output, @Name = N'Sample Weblog', @Description = N'', @ParentID = 0, @GroupID = @GroupID, @IsModerated = 0, @DisplayPostsOlderThan = 7, @IsActive = 1, @EnablePostStatistics = 1, @EnableAutoDelete = 0, @EnableAnonymousPosting = 0, @AutoDeleteThreshold = 90, @SortOrder = 0, @ApplicationType = 1, @ApplicationKey = N'sample_weblog', @PropertyNames = N'SectionOwners:S:0:5:', @PropertyValues = N'admin', @SettingsID = @SettingsID, @UserID = @UserID



declare @CategoryID int
exec dbo.cs_PostCategory_CreateUpdateDelete @SectionID = @SectionID, @Name = N'Blogging', @IsEnabled = 1, @ParentID = 0, @Description = N'This category is about blogging', @CategoryID = @CategoryID output, @SettingsID = @SettingsID



Declare @PostID int
Declare @Date datetime
Set @Date = GetDate()
declare @PostStickyDate DateTime
set @PostStickyDate = CONVERT(DATETIME, '17530101 12:00:00', 112)
exec dbo.cs_weblog_Post_Create @SectionID = @SectionID, @ParentID = 0, @AllowDuplicatePosts = 1, @DuplicateIntervalInMinutes = 1, @Subject = N'Welcome to Community Server Blogs!', @IsLocked = 0, @IsApproved = 1, @IsTracked = 0, @PostType = 1, @EmoticonID = 0, @UserID = @UserID, @Body = N'
		<p>A weblog (blog) is an online journal you can use to share thoughts, ideas, gripes, project status, or anything else you want. Blogs allow you to be a contributor rather than just a bystander.</p>
		<p>Postings are arranged chronologically and can be categorized depending upon how the administrator has configured the system. You can view a post by clicking on the title from the home page where all users'' posts are collectively shown. Once viewing a blog you can read other posts by that person or provide comments on postings.</p>
		<p>Creating new posts is quick and easy. If you have the ability to post you should see a link (usually on the left) on your weblog''s home page: new post. Clicking on this link takes you into your blogs administration pages for creating new posts.</p>
		<p>If you don''t have the ability to post, contact the site administrator and ask for your own blog.</p>
		<p>Happy Blogging!</p>
', @FormattedBody = N'
		<p>A weblog (blog) is an online journal you can use to share thoughts, ideas, gripes, project status, or anything else you want. Blogs allow you to be a contributor rather than just a bystander.</p>
		<p>Postings are arranged chronologically and can be categorized depending upon how the administrator has configured the system. You can view a post by clicking on the title from the home page where all users'' posts are collectively shown. Once viewing a blog you can read other posts by that person or provide comments on postings.</p>
		<p>Creating new posts is quick and easy. If you have the ability to post you should see a link (usually on the left) on your weblog''s home page: new post. Clicking on this link takes you into your blogs administration pages for creating new posts.</p>
		<p>If you don''t have the ability to post, contact the site administrator and ask for your own blog.</p>
		<p>Happy Blogging!</p>', @UserHostAddress = N'127.0.0.1', @PostDate = @Date, @UserTime = @Date, @PropertyNames = N'EnableRatings:S:0:4:EnableTrackBacks:S:4:4:', @PropertyValues = N'TrueTrue', @SettingsID = @SettingsID, @IsSticky = 0, @StickyDate = @PostStickyDate, @PostName = N'My First Post', @PostConfig = 11, @BlogPostType = 1, @Categories = N'<Categories><Category>Blogging</Category></Categories>', @PostID = @PostID output

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_system_SampleWeblog] to public
go

/***********************************************
* Sproc: cs_system_UpdateForum
* File Date: 11/29/2006 10:07:30 AM
***********************************************/
Print 'Creating...cs_system_UpdateForum'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_system_UpdateForum]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_system_UpdateForum]
GO


CREATE PROCEDURE [dbo].cs_system_UpdateForum
(
	@SectionID int,
	@ThreadID int,
	@PostID int,
	@SettingsID int,
	@UpdateThreadDate bit = 1, -- new param with a default value,
	@PostDisplayName nvarchar(64) = null
)
AS
SET Transaction Isolation Level Read UNCOMMITTED
BEGIN

DECLARE @UserID 		int
DECLARE @PostDate 		datetime
DECLARE @TotalThreads 		int
DECLARE @TotalPosts 		int
DECLARE @PostsToModerate	int
DECLARE @Subject		nvarchar(64)
DECLARE @User 		nvarchar(64)
DECLARE @PostConfiguration	int
DECLARE @IsApproved bit


-- Set default
SET @PostConfiguration = 0

-- Get values necessary to update the forum statistics
SELECT
	@IsApproved = P.IsApproved,
	@UserID = P.UserID,
	@PostDate = PostDate,
	@TotalPosts = (SELECT COUNT(PostID) FROM cs_Posts WHERE SectionID = @SectionID AND IsApproved = 1 and SettingsID = @SettingsID),
	@TotalThreads = (SELECT COUNT(P2.PostID) FROM cs_Posts P2 (nolock) WHERE P2.SectionID = @SectionID AND P2.IsApproved=1 AND P2.PostLevel=1 and P2.SettingsID = @SettingsID),
	@PostsToModerate = (SELECT Count(PostID) FROM cs_Posts WHERE SectionID = @SectionID AND IsApproved = 0 and SettingsID = @SettingsID),
	@Subject = P.Subject,
	@User = PostAuthor,
	@PostConfiguration = P.PostConfiguration
FROM
	cs_Posts P
WHERE
	PostID = @PostID and P.SettingsID = @SettingsID and P.SectionID = @SectionID

-- Is anonymous post?
IF (@PostConfiguration & 1) = 1
BEGIN
	-- Set anonymous info instead real user info
	SELECT @UserID = cs_UserID FROM cs_vw_Users_FullUser WHERE SettingsID = @SettingsID and IsAnonymous = 1	
	SET @User = null
	SET @PostDisplayName = null
	
END

IF (@PostConfiguration & 2) <> 2 -- Check to make sure that the post is not flagged as ignored. 
BEGIN 
	-- We need to separate the process of updating a thread info into 2 steps:
	-- 1. first update the strings and counters
	-- 2. update MostRecentPostDate separatelly because there are situations when 
	-- we need to update info but not the date. Eg: anonymous user posting - when
	-- post's owner choose to become visible on editing its post.

	-- Always update counters
	UPDATE 
		cs_Sections
	SET
		TotalPosts = isnull(@TotalPosts,0),
		TotalThreads = isnull(@TotalThreads,0),
		PostsToModerate = isnull(@PostsToModerate,0)
	WHERE
		SectionID = @SectionID and SettingsID = @SettingsID

	-- Only update Post-specific info if the current post is approved
	IF @IsApproved = 1
	BEGIN
		UPDATE 
			cs_Sections
		SET
			MostRecentPostID = isnull(@PostID,0),
			MostRecentThreadID = isnull(@ThreadID,0),
			MostRecentPostAuthorID = isnull(@UserID,0),
			MostRecentPostSubject = isnull(@Subject,''),
			MostRecentPostAuthor = isnull(@PostDisplayName,isnull(@User,'')),
			MostRecentThreadReplies = ISNULL((SELECT TotalReplies FROM cs_Threads WHERE ThreadID = @ThreadID), 0)
		WHERE
			SectionID = @SectionID and SettingsID = @SettingsID
	
		IF @UpdateThreadDate = 1
			UPDATE 
				cs_Sections
			SET
				MostRecentPostDate = isnull(@PostDate,'1/01/1797')
			WHERE
				SectionID = @SectionID and SettingsID = @SettingsID
	
		-- UPDATE Parent
		DECLARE @ParentID int
		SELECT @ParentID = ParentID FROM cs_Sections where SectionID = @SectionID
	
		WHILE @ParentID > 0
		BEGIN
			UPDATE 
				cs_Sections
			SET
				MostRecentPostID = isnull(@PostID,0),
				MostRecentThreadID = isnull(@ThreadID,0),
				MostRecentPostAuthorID = isnull(@UserID,0),
				MostRecentPostSubject = isnull(@Subject,''),
				MostRecentPostAuthor = isnull(@User,''),
				MostRecentThreadReplies = ISNULL((SELECT TotalReplies FROM cs_Threads WHERE ThreadID = @ThreadID), 0)
			WHERE
				SectionID = @ParentID and SettingsID = @SettingsID
	
			-- Get the next ParentID
			SELECT @ParentID = ParentID FROM cs_Sections where SectionID = @ParentID
		END
	
	END

END

END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_system_UpdateForum] to public
go

/***********************************************
* Sproc: cs_system_UpdateMostActiveUsers
* File Date: 11/29/2006 10:07:29 AM
***********************************************/
Print 'Creating...cs_system_UpdateMostActiveUsers'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_system_UpdateMostActiveUsers]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_system_UpdateMostActiveUsers]
GO



CREATE   procedure [dbo].cs_system_UpdateMostActiveUsers
(
	@SettingsID int
)
AS
SET Transaction Isolation Level Read UNCOMMITTED
BEGIN
	SET NOCOUNT ON

	DELETE FROM cs_statistics_User WHERE SettingsID = @SettingsID
	
	INSERT INTO cs_statistics_User
	SELECT TOP 100
		U.cs_UserID,
		TotalPosts = ISNULL( (SELECT count(PostID) FROM cs_Posts, cs_Sections WHERE cs_Sections.ApplicationType = 0 and cs_Sections.SectionID = cs_Posts.SectionID and cs_Sections.SettingsID = @SettingsID AND UserID = U.cs_UserID AND PostDate > DateAdd(day, -1, GetDate())), 0),
		@SettingsID
	FROM
		cs_vw_Users_FullUser U
	WHERE
		U.IsAnonymous = 0 AND
		U.IsIgnored = 0   AND
		U.cs_UserAccountStatus = 1 and U.SettingsID = @SettingsID
	ORDER BY
		TotalPosts DESC

	SET NOCOUNT OFF
END





GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_system_UpdateMostActiveUsers] to public
go
/***********************************************
* Sproc: cs_system_UpdateSite
* File Date: 11/29/2006 10:07:30 AM
***********************************************/
Print 'Creating...cs_system_UpdateSite'

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_system_UpdateSite]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_system_UpdateSite]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO






CREATE PROCEDURE [dbo].[cs_system_UpdateSite]
(
	@UpdateUserPostRank bit = 1,
	@UpdateMostActiveUserList bit = 1,
	@SettingsID int,
	@UpdateWindow int = 3
)
AS

-- Do we need to update the statistics?
DECLARE @LastUpdate datetime
DECLARE @DateWindow datetime
DECLARE @ApplicationId uniqueidentifier
DECLARE @ModeratorRoleID AS uniqueidentifier

SET @ApplicationId = (SELECT ApplicationId FROM aspnet_Applications A, cs_SiteSettings S WHERE A.ApplicationName = S.ApplicationName AND SettingsID = @SettingsID)
SET @ModeratorRoleID = (SELECT RoleId from aspnet_Roles WHERE LoweredRoleName = 'moderator' AND ApplicationId = @ApplicationId)
SET @LastUpdate = ISNULL((SELECT MAX(DateCreated) FROM cs_statistics_Site where SettingsID = @SettingsID), '1/1/1797')
SET @DateWindow = DATEADD(hh, -@UpdateWindow, GetDate())

if (@LastUpdate <  @DateWindow)
BEGIN


	-- Get summary information - Total Users, Total Posts, TotalTopics, DaysPosts, and DaysTopics
	DECLARE @LastDateTimeUpdate datetime
	DECLARE @TotalUsers int
	DECLARE @TotalPosts int
	DECLARE @TotalTopics int
	DECLARE @TotalModerators int
	DECLARE @TotalModeratedPosts int
	DECLARE @NewThreadsInPast24Hours int
	DECLARE @NewPostsInPast24Hours int
	DECLARE @NewUsersInPast24Hours int
	DECLARE @MostViewsPostID int
        DECLARE @ViewCount int
	DECLARE @MostActivePostID int
	DECLARE @ReplyCount int
	DECLARE @MostReadPostID int
	DECLARE @TotalAnonymousUsers int
	DECLARE @NewestUserID int
	DECLARE @MostActiveUserID int
	DECLARE @ApplicationName  NVARCHAR(256)

	SET @ApplicationName  = (Select Lower(ApplicationName) FROM cs_SiteSettings where SettingsID = @SettingsID)



	SET NOCOUNT ON

	SET @LastDateTimeUpdate = ISNULL( 
					(
						SELECT TOP 1
							DateCreated 
						FROM 
							cs_statistics_Site where SettingsID = @SettingsID
					), '1/1/1979 12:00:00')

	-- Reset top posters
	IF @UpdateUserPostRank = 1
		exec cs_system_UpdateUserPostRank @SettingsID

	IF @UpdateMostActiveUserList = 1
		exec cs_system_UpdateMostActiveUsers @SettingsID

	-- Total Anonymous Users
	-- ***********************************************
	SET @TotalAnonymousUsers = 0-- ISNULL((SELECT COUNT(UserID) FROM cs_AnonymousUsers where SettingsID = @SettingsID), 0 )

	-- Total Moderators, for this site only
	-- ***********************************************
	SET @TotalModerators = ISNULL(
					(
						SELECT 
							COUNT(*) 
						FROM 
							aspnet_UsersInRoles jUR
							JOIN aspnet_Roles jR ON jR.RoleID = jUR.RoleID
							JOIN aspnet_applications jA on jR.ApplicationId = jA.ApplicationId			
						WHERE 
							jR.LoweredRoleName = 'moderator' and LOWER(@ApplicationName) = jA.LoweredApplicationName
					), 0)

	-- Total Moderated Posts
	-- ***********************************************
	SET @TotalModeratedPosts  = 	ISNULL( 
					(
						SELECT TOP 1 
							TotalModeratedPosts 
						FROM 
							cs_statistics_Site where SettingsID = @SettingsID 
					), 0) + 
					ISNULL( 
					(
						SELECT 
							COUNT(ModerationAction) 
						FROM 
							cs_ModerationAudit 
						WHERE 
							ModeratedOn >= @LastDateTimeUpdate AND
							SettingsID = @SettingsID AND
							ModerationAction = 1
					), 0)
	IF @TotalModeratedPosts = 0
	BEGIN
		-- there was no previous count.  this is mainly for clean installs
		SET @TotalModeratedPosts = (SELECT COUNT(ModerationAction) FROM cs_ModerationAudit WHERE SettingsID = @SettingsID AND ModerationAction = 1)
	END

	-- Most "Viewed" thread, by grabbing the first post
	-- ***********************************************
	SET @MostViewsPostID = ISNULL(
					(
						SELECT TOP 1 
							jP1.PostID
						FROM 
							cs_Threads jT
							JOIN cs_Posts jP1 ON jP1.ThreadID = jT.ThreadID
							JOIN cs_vw_EveryOne_Role jE ON jE.LoweredApplicationName = @ApplicationName
							JOIN cs_ProductPermissions jP ON (jP.RoleID = jE.RoleId and jP.ApplicationType = 0)
							LEFT JOIN cs_SectionPermissions jP2 ON (jP2.RoleID = jE.RoleId and jP2.SectionID = jT.SectionID)
							JOIN cs_Sections jF on jT.SectionID = jF.SectionID
						WHERE 
							isnull(jP2.AllowMask,jP.AllowMask) & convert(bigint,0x0000000000000001) = convert(bigint,0x0000000000000001) AND
							jT.ThreadDate > DateAdd(d, -3, GetDate()) AND
							jP1.IsApproved = 1 AND
							jF.ForumType = 0 and jF.ApplicationType = 0 and jP1.SettingsID = @SettingsID
						ORDER BY 
							jT.TotalViews DESC
					), 0)

        -- "ViewCount" thread, by grabbing the first post
	-- ***********************************************
	SET @ViewCount = ISNULL(
					(
						SELECT TOP 1 
							jP1.TotalViews
						FROM 
							cs_Threads jT
							JOIN cs_Posts jP1 ON jP1.ThreadID = jT.ThreadID
							JOIN cs_vw_EveryOne_Role jE ON jE.LoweredApplicationName = @ApplicationName
							JOIN cs_ProductPermissions jP ON (jP.RoleID = jE.RoleId and jP.ApplicationType = 0)
							LEFT JOIN cs_SectionPermissions jP2 ON (jP2.RoleID = jE.RoleId and jP2.SectionID = jT.SectionID)
							JOIN cs_Sections jF on jT.SectionID = jF.SectionID
						WHERE 
							isnull(jP2.AllowMask,jP.AllowMask) & convert(bigint,0x0000000000000001) = convert(bigint,0x0000000000000001) AND
							jT.ThreadDate > DateAdd(d, -3, GetDate()) AND
							jP1.IsApproved = 1 AND
							jF.ForumType = 0 and jF.ApplicationType = 0 and jP1.SettingsID = @SettingsID
						ORDER BY
							jT.TotalViews DESC
					), 0)


	-- Most "Active" Thread, by grabbing the first post
	-- ***********************************************
	SET @MostActivePostID = ISNULL(
					(
						SELECT TOP 1 
							jP1.PostID
						FROM 
							cs_Threads jT
							JOIN cs_Posts jP1 ON jP1.ThreadID = jT.ThreadID
							JOIN cs_vw_EveryOne_Role jE ON jE.LoweredApplicationName = @ApplicationName
							JOIN cs_ProductPermissions jP ON (jP.RoleID = jE.RoleId and jP.ApplicationType = 0)
							LEFT JOIN cs_SectionPermissions jP2 ON (jP2.RoleID = jE.RoleId and jP2.SectionID = jT.SectionID)
							JOIN cs_Sections jF on jP1.SectionID = jF.SectionID
						WHERE 
							isnull(jP2.AllowMask,jP.AllowMask) & convert(bigint,0x0000000000000001) = convert(bigint,0x0000000000000001) AND
							jT.ThreadDate > DateAdd(d, -3, GetDate()) AND
							jP1.IsApproved = 1 AND
							jF.ForumType = 0 and jF.ApplicationType = 0 and jP1.SettingsID = @SettingsID		-- excluding PM and hidden forums
						ORDER BY 
							jT.TotalReplies DESC
					), 0)

        -- "ReplyCount" on a Thread, by grabbing the first post
	-- ***********************************************
	SET @ReplyCount = ISNULL(
					(
						SELECT TOP 1 
							jT.TotalReplies
						FROM 
							cs_Threads jT
							JOIN cs_Posts jP1 ON jP1.ThreadID = jT.ThreadID
							JOIN cs_vw_EveryOne_Role jE ON jE.LoweredApplicationName = @ApplicationName
							JOIN cs_ProductPermissions jP ON (jP.RoleID = jE.RoleId and jP.ApplicationType = 0)
							LEFT JOIN cs_SectionPermissions jP2 ON (jP2.RoleID = jE.RoleId and jP2.SectionID = jT.SectionID)
							JOIN cs_Sections jF on jP1.SectionID = jF.SectionID
						WHERE 
							isnull(jP2.AllowMask,jP.AllowMask) & convert(bigint,0x0000000000000001) = convert(bigint,0x0000000000000001) AND
							jT.ThreadDate > DateAdd(d, -3, GetDate()) AND
							jP1.IsApproved = 1 AND
							jF.ForumType = 0 and jF.ApplicationType = 0 and jP1.SettingsID = @SettingsID		-- excluding PM and hidden forums
						ORDER BY 
							jT.TotalReplies DESC
					), 0)

	-- Most "Read" thread, by grabbing the first post
	-- ***********************************************
	SET @MostReadPostID = ISNULL(
					(
						SELECT TOP 1 
							jP1.PostID
						FROM 
							cs_Threads jT
							JOIN cs_Posts jP1 ON jP1.ThreadID = jT.ThreadID
							JOIN cs_vw_EveryOne_Role jE ON jE.LoweredApplicationName = @ApplicationName
							JOIN cs_ProductPermissions jP ON (jP.RoleID = jE.RoleId and jP.ApplicationType = 0)
							LEFT JOIN cs_SectionPermissions jP2 ON (jP2.RoleID = jE.RoleId and jP2.SectionID = jT.SectionID)
							JOIN cs_Sections jF on jP1.SectionID = jF.SectionID
						WHERE 
							isnull(jP2.AllowMask,jP.AllowMask) & convert(bigint,0x0000000000000001) = convert(bigint,0x0000000000000001) AND
							jT.ThreadDate > DateAdd(d, -3, GetDate()) AND
							jP1.IsApproved = 1 AND
							jF.ForumType = 0 and jF.ApplicationType = 0 and jF.SettingsID = @SettingsID		-- excluding PM and hidden forums
						ORDER BY 
							( SELECT count(jTR.ThreadID) FROM cs_ThreadsRead jTR WHERE jP1.ThreadID = jTR.ThreadID ) DESC
					), 0)


	-- Most active user
	-- ***********************************************
	SET @MostActiveUserID = ISNULL(
					(
						SELECT TOP 1 
							--jU.cs_UserID
							jP.UserID
						FROM 
							--cs_vw_Users_FullUser jU JOIN 
							cs_UserProfile jP --ON jP.UserID = jU.cs_UserID
						WHERE
							jP.EnableDisplayInMemberList = 1 and jP.SettingsID = @SettingsID
						ORDER BY 
							jP.TotalPosts DESC
					), 0)
	-- Newest user
	-- ***********************************************
	SET @NewestUserID = ISNULL(
					(
						SELECT Max(ju.cs_UserID) 

						FROM 
							cs_vw_Users_FullUser jU
							JOIN cs_UserProfile jP ON jP.UserID = jU.cs_UserID
						WHERE
							jP.EnableDisplayInMemberList = 1 AND
							jU.cs_UserAccountStatus = 1 and jP.SettingsID = @SettingsID
						--ORDER BY jU.CreateDate DESC
					), 0)


	-- Total Users
	-- ***********************************************
	SET @TotalUsers = ISNULL( 
					(
						SELECT 
							COUNT(UserID) 
						FROM 
							cs_UserProfile 
						WHERE 
							--EnableDisplayInMemberList = 1 and SettingsID = @SettingsID
							SettingsID = @SettingsID
					) ,0) 


	-- Total Posts
	-- ***********************************************
	SET @TotalPosts = 	ISNULL( 
					(
						SELECT TOP 1 
							TotalPosts 
						FROM 
							cs_statistics_Site where SettingsID = @SettingsID 
					), 0) +
				 ISNULL( 
					(
						SELECT 
							COUNT(PostID) 
						FROM 
							cs_Posts, cs_Sections
						WHERE 
							ForumType = 0 and cs_Posts.SectionID = cs_Sections.SectionID and 
						PostDate >= @LastDateTimeUpdate and cs_Sections.SettingsID = @SettingsID and cs_Sections.ApplicationType = 0
					), 0)
	IF @TotalPosts = 0
	BEGIN
		-- there was no previous count.  this is mainly for clean installs
		SET @TotalPosts = (SELECT COUNT(PostID) FROM cs_Posts WHERE SettingsID = @SettingsID)
	END


	-- Total Topics
	-- ***********************************************
	SET @TotalTopics = 	ISNULL( 
					(
						SELECT TOP 1 
							TotalTopics 
						FROM 
							cs_statistics_Site where SettingsID = @SettingsID 
					), 0) + 
				ISNULL( 
					(
						SELECT 
							COUNT(ThreadID) 
						FROM 
							cs_Threads, cs_Sections 
						WHERE 
							ForumType = 0 AND cs_Threads.SectionID = cs_Sections.SectionID and 
							ThreadDate >= @LastDateTimeUpdate and cs_Sections.SettingsID = @SettingsID and cs_Sections.ApplicationType = 0
					), 0)
	IF @TotalTopics = 0
	BEGIN
		-- there was no previous count.  this is mainly for clean installs
		SET @TotalTopics = (SELECT COUNT(ThreadID) FROM cs_Threads, cs_Sections WHERE cs_Sections.SettingsID = @SettingsID and ForumType = 0 and cs_Sections.SectionID = cs_Threads.SectionID and cs_Sections.ApplicationType = 0)
	END

	-- Total Posts in past 24 hours
	-- ***********************************************
	SET @NewPostsInPast24Hours = ISNULL( 
					(SELECT COUNT(PostID) FROM cs_Posts, cs_Sections WHERE cs_Sections.ApplicationType = 0 and cs_Sections.SettingsID = @SettingsID And cs_Sections.SectionID = cs_Posts.SectionID and ForumType = 0 and PostDate > DATEADD(dd,-1,getdate())
					), 0)

	-- Total Users in past 24 hours
	-- ***********************************************
	SET @NewUsersInPast24Hours = ISNULL(
						(SELECT COUNT(IsApproved) FROM aspnet_Membership WHERE ApplicationId = @ApplicationId and CreateDate > DATEADD(dd,-1,getdate())
					), 0)

	-- Total Topics in past 24 hours
	-- ***********************************************
	SET @NewThreadsInPast24Hours = ISNULL(
						(SELECT COUNT(ThreadID) FROM cs_Threads, cs_Sections WHERE cs_Sections.SectionID = cs_Threads.SectionID AND cs_Sections.SettingsID = @SettingsID and ForumType = 0 and cs_Sections.ApplicationType = 0 AND PostDate > DATEADD(dd,-1,getdate())
					), 0)

	INSERT INTO cs_statistics_Site
	SELECT 
		DateCreated = GetDate(),
		TotalUsers = @TotalUsers,
		TotalPosts = @TotalPosts,
		TotalModerators = @TotalModerators,
		TotalModeratedPosts = @TotalModeratedPosts,
		TotalAnonymousUsers = @TotalAnonymousUsers,
		TotalTopics = @TotalTopics,
		DaysPosts = @NewPostsInPast24Hours, -- TODO remove
		DaysTopics = @NewThreadsInPast24Hours, -- TODO remove
		NewPostsInPast24Hours = @NewPostsInPast24Hours,
		NewThreadsInPast24Hours = @NewThreadsInPast24Hours,
		NewUsersInPast24Hours = @NewUsersInPast24Hours,
		MostViewsPostID = @MostViewsPostID,
		MostActivePostID = @MostActivePostID,
		MostActiveUserID = @MostActiveUserID,
		MostReadPostID = @MostReadPostID,
		NewestUserID = @NewestUserID,	
		SettingsID = @SettingsID,
        	ViewCount = @ViewCount,
        	ReplyCount = @ReplyCount
END

SET NOCOUNT OFF






GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_system_UpdateSite] to public
go

/***********************************************
* Sproc: cs_system_UpdateSubscriptions
* File Date: 11/29/2006 10:07:31 AM
***********************************************/
Print 'Creating...cs_system_UpdateSubscriptions'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_system_UpdateSubscriptions]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_system_UpdateSubscriptions]
GO

CREATE PROCEDURE [dbo].cs_system_UpdateSubscriptions
(
	@RoleID uniqueidentifier,
	@SectionID int,
	@SettingsID int
)
AS
/*
	Remove users subscriptions based on provided role ID.
*/
SET Transaction Isolation Level Read UNCOMMITTED
BEGIN

	DECLARE @UserID int
	DECLARE @HasAccess bit
	
	DECLARE users_cursor CURSOR FOR 
	SELECT UserID FROM cs_vw_UsersInRoles WHERE RoleId = @RoleID

	OPEN users_cursor

	FETCH NEXT FROM users_cursor 
	INTO @UserID

	WHILE @@FETCH_STATUS = 0
	BEGIN
		-- Get user's view & read access permissions status
		EXEC @HasAccess = cs_system_UserCanReadSection @UserID, @SectionID, @SettingsID
		
		-- If no access then clean up subscriptions
		IF @HasAccess = 0
		BEGIN
			-- Remove forum subscriptions
			EXEC cs_RemoveAllSectionTracking @UserID, @SectionID, @SettingsID

			-- Remove thread subscriptions
			EXEC cs_RemoveAllPostTracking @UserID, @SectionID, @SettingsID
		END

		FETCH NEXT FROM users_cursor
		INTO @UserID
	END

	CLOSE users_cursor
	DEALLOCATE users_cursor

END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_system_UpdateSubscriptions] to public


/***********************************************
* Sproc: cs_system_UpdateThread
* File Date: 11/29/2006 10:07:31 AM
***********************************************/
Print 'Creating...cs_system_UpdateThread'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_system_UpdateThread]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_system_UpdateThread]
GO


CREATE PROCEDURE [dbo].cs_system_UpdateThread
(
	@ThreadID int,
	@ReplyPostID int,
	@SettingsID int,
	@UpdateThreadDate bit = 1 -- new param with a default value
)
AS
SET Transaction Isolation Level Read UNCOMMITTED
BEGIN

SET NOCOUNT ON

DECLARE @ThreadDate datetime
DECLARE @StickyDate datetime
DECLARE @UserID int
DECLARE @PostAuthor nvarchar(64)
DECLARE @FirstPostID INT
DECLARE @PostConfiguration int

-- Set default
SET @PostConfiguration = 0

IF @ReplyPostID = 0
	SELECT TOP 1 
		@ReplyPostID = PostID 
	FROM 
		cs_Posts
	WHERE
		ThreadID = @ThreadID
		AND IsApproved = 1 and SettingsID = @SettingsID
	ORDER BY
		PostDate DESC

-- Get details about the reply & PostConfiguration details
SELECT 
	@ThreadDate = PostDate, 
	@UserID = UserID, 
	@PostAuthor = PostAuthor,
	@PostConfiguration = PostConfiguration
FROM 
	cs_Posts 
WHERE 
	PostID = @ReplyPostID and SettingsID = @SettingsID

-- Is anonymous post?
IF (@PostConfiguration & 1) = 1
BEGIN
	-- Set anonymous info instead real user info
	SELECT @UserID = cs_UserID FROM cs_vw_Users_FullUser WHERE SettingsID = @SettingsID and IsAnonymous = 1
	SET @PostAuthor = ''
END

SELECT 
	@StickyDate = StickyDate 
FROM 
	cs_Threads 
WHERE 
	ThreadID = @ThreadID and SettingsID = @SettingsID

IF @StickyDate < @ThreadDate
	SET @StickyDate = @ThreadDate

-- do the mass updates.
IF (@PostConfiguration & 2) <> 2 -- Check to make sure that the most recent post hasn't been flagged as ignored. 
BEGIN
	-- We need to separate the process of updating a thread info into 2 steps:
	-- 1. first update the strings and counters
	-- 2. update MostRecentPostDate separatelly because there are situations when 
	-- we need to update info but not the date. Eg: anonymous user posting - when
	-- post's owner choose to become visible on editing its post.

	UPDATE 
		cs_Threads
	SET
		TotalReplies = (SELECT Count(PostID) FROM cs_Posts WHERE ThreadID = @ThreadID AND IsApproved = 1 AND PostLevel > 1),
		MostRecentPostAuthorID = @UserID,
		MostRecentPostAuthor = @PostAuthor,
		MostRecentPostID = @ReplyPostID
	WHERE
		ThreadID = @ThreadID and SettingsID = @SettingsID
	
	IF @UpdateThreadDate = 1	
		UPDATE 
			cs_Threads
		SET
			ThreadDate = @ThreadDate,
			StickyDate = @StickyDate
		WHERE
			ThreadID = @ThreadID and SettingsID = @SettingsID
END

-- find any lingering ParentIDs that don't match any posts in
-- our thread (from a merge or split action)
SET @FirstPostID = (	
	SELECT TOP 1 
		PostID 
	FROM 
		cs_Posts
	WHERE
		ThreadID = @ThreadID
		AND IsApproved = 1 and SettingsID = @SettingsID
	ORDER BY
		PostDate ASC 
	)

UPDATE
	cs_Posts
SET
	ParentID = @FirstPostID
WHERE
	ParentID NOT IN (SELECT PostID FROM cs_Posts WHERE ThreadID = @ThreadID and SettingsID = @SettingsID)
	AND ThreadID = @ThreadID and SettingsID = @SettingsID


-- fix the PostLevel and SortOrder ordering, by date
-- this could be done better, as it's on a MassScale now.
UPDATE
	cs_Posts
SET
	PostLevel = 1,
	SortOrder = 1
WHERE
	ThreadID = @ThreadID
	AND PostID = (SELECT TOP 1 PostID FROM cs_Posts WHERE ThreadID = @ThreadID and SettingsID = @SettingsID ORDER BY PostID ASC)

UPDATE
	cs_Posts
SET
	PostLevel = 2,
	SortOrder = SortOrder + 1
WHERE
	ThreadID = @ThreadID
	AND PostID > @ReplyPostID and SettingsID = @SettingsID

-- update the EmoticonID, if it's the first post
IF @ReplyPostID = (SELECT TOP 1 PostID FROM cs_Posts WHERE ThreadID = @ThreadID and SettingsID = @SettingsID ORDER BY PostDate ASC)
	UPDATE
		cs_Threads
	SET
		ThreadEmoticonID = (SELECT EmoticonID FROM cs_Posts WHERE PostID = @ReplyPostID and SettingsID = @SettingsID)
	WHERE
		ThreadID = @ThreadID	 and SettingsID = @SettingsID

SET NOCOUNT OFF

END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



grant execute on [dbo].[cs_system_UpdateThread] to public
go
/***********************************************
* Sproc: cs_system_UpdateUserPostCount
* File Date: 11/29/2006 10:07:30 AM
***********************************************/
Print 'Creating...cs_system_UpdateUserPostCount'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_system_UpdateUserPostCount]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_system_UpdateUserPostCount]
GO





create  procedure [dbo].cs_system_UpdateUserPostCount
(
	@SectionID 	int,
	@UserID		int,
	@SettingsID 	int,
	@UpdateAllSettingsID bit = 0
)
AS
SET Transaction Isolation Level Read UNCOMMITTED
BEGIN

	-- Does the forum track post statistics?
	IF (SELECT EnablePostStatistics FROM cs_Sections WHERE SectionID = @SectionID and SettingsID = @SettingsID) = 0
		RETURN

	UPDATE cs_UserProfile SET TotalPosts = TotalPosts + 1 WHERE UserID = @UserID and (SettingsID = @SettingsID or @UpdateAllSettingsID = 1)

END





















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_system_UpdateUserPostCount] to public
go
/***********************************************
* Sproc: cs_system_UpdateUserPostRank
* File Date: 11/29/2006 10:07:29 AM
***********************************************/
Print 'Creating...cs_system_UpdateUserPostRank'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_system_UpdateUserPostRank]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_system_UpdateUserPostRank]
GO





create      procedure [dbo].cs_system_UpdateUserPostRank
(
	@SettingsID int
)
AS
SET Transaction Isolation Level Read UNCOMMITTED
BEGIN
DECLARE @Usercount int
DECLARE @LoopCounter int

	SET NOCOUNT ON

	CREATE Table #PostRank (
	  Rank int IDENTITY (1, 1) NOT NULL,
	  UserID int
	)

	-- Select into temp table
	INSERT INTO #PostRank (UserID)
	SELECT TOP 500
		P.UserID
	FROM
		cs_UserProfile P
	Where SettingsID = @SettingsID
	ORDER BY
		P.TotalPosts DESC

	-- How many users did we select?
	SELECT @Usercount = count(*) FROM #PostRank


	-- First clear all the users
	UPDATE 
		cs_UserProfile
	SET 
		PostRank = 0x0
	WHERE 
		PostRank > 0 and SettingsID = @SettingsID

	-- Top 10
	UPDATE
		cs_UserProfile
	SET
		PostRank = 0x01
	WHERE
		UserID in (SELECT UserID FROM #PostRank WHERE Rank < 11 and SettingsID = @SettingsID) and SettingsID = @SettingsID

	-- Top 25
	UPDATE
		cs_UserProfile
	SET
		PostRank = 0x02
	WHERE
		UserID in (SELECT UserID FROM #PostRank WHERE Rank > 10 AND Rank < 26 and SettingsID = @SettingsID) and SettingsID = @SettingsID


	-- Top 50
	UPDATE
		cs_UserProfile
	SET
		PostRank = 0x04
	WHERE
		UserID in (SELECT UserID FROM #PostRank WHERE Rank > 25 AND Rank < 51 and SettingsID = @SettingsID) and SettingsID = @SettingsID


	-- Top 75
	UPDATE
		cs_UserProfile
	SET
		PostRank = 0x08
	WHERE
		UserID in (SELECT UserID FROM #PostRank WHERE Rank > 50 AND Rank < 76 and SettingsID = @SettingsID) and SettingsID = @SettingsID

	-- Top 100
	UPDATE
		cs_UserProfile
	SET
		PostRank = 0x10
	WHERE
		UserID in (SELECT UserID FROM #PostRank WHERE Rank > 75 AND Rank < 101 and SettingsID = @SettingsID) and SettingsID = @SettingsID

	-- Top 150
	UPDATE
		cs_UserProfile
	SET
		PostRank = 0x20
	WHERE
		UserID in (SELECT UserID FROM #PostRank WHERE Rank > 100 AND Rank < 151 and SettingsID = @SettingsID) and SettingsID = @SettingsID

	-- Top 200
	UPDATE
		cs_UserProfile
	SET
		PostRank = 0x40
	WHERE
		UserID in (SELECT UserID FROM #PostRank WHERE Rank > 150 AND Rank < 200 and SettingsID = @SettingsID) and SettingsID = @SettingsID


	-- Top 500
	UPDATE
		cs_UserProfile
	SET
		PostRank = 0x80
	WHERE
		UserID in (SELECT UserID FROM #PostRank WHERE Rank > 200 and SettingsID = @SettingsID) and SettingsID = @SettingsID

END





























GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_system_UpdateUserPostRank] to public
go
/***********************************************
* Sproc: cs_system_UpdateUserSubscriptions
* File Date: 11/29/2006 10:07:34 AM
***********************************************/
Print 'Creating...cs_system_UpdateUserSubscriptions'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_system_UpdateUserSubscriptions]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_system_UpdateUserSubscriptions]
GO

CREATE PROCEDURE [dbo].cs_system_UpdateUserSubscriptions
(
	@UserID int,
	@SettingsID int
)
AS
SET Transaction Isolation Level Read UNCOMMITTED
BEGIN

	DECLARE @SectionID int
	DECLARE @HasAccess bit
	
	DECLARE sections_cursor CURSOR FOR
	SELECT T.SectionID
	FROM cs_TrackedThreads TT INNER JOIN cs_Threads T ON TT.ThreadID = T.ThreadID
	WHERE TT.UserID = @UserID AND TT.SettingsID = @SettingsID
	UNION
	SELECT TS.SectionID
	FROM cs_TrackedSections TS
	WHERE TS.UserID = @UserID AND TS.SettingsID = @SettingsID
	
	OPEN sections_cursor

	FETCH NEXT FROM sections_cursor 
	INTO @SectionID

	WHILE @@FETCH_STATUS = 0
	BEGIN
		-- Get user's view & read access permissions status
		EXEC @HasAccess = cs_system_UserCanReadSection @UserID, @SectionID, @SettingsID
		
		-- If no access then clean up subscriptions
		IF @HasAccess = 0
		BEGIN
			-- Remove forum subscriptions
			EXEC cs_RemoveAllSectionTracking @UserID, @SectionID, @SettingsID

			-- Remove thread subscriptions
			EXEC cs_RemoveAllPostTracking @UserID, @SectionID, @SettingsID
		END

		FETCH NEXT FROM sections_cursor
		INTO @SectionID
	END

	CLOSE sections_cursor
	DEALLOCATE sections_cursor

END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_system_UpdateUserSubscriptions] to public


/***********************************************
* Sproc: cs_system_UserCanReadSection
* File Date: 11/29/2006 10:07:31 AM
***********************************************/
Print 'Creating...cs_system_UserCanReadSection'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_system_UserCanReadSection]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_system_UserCanReadSection]
GO

CREATE PROCEDURE [dbo].cs_system_UserCanReadSection
(
	@UserID int,
	@SectionID int,
	@SettingsID int
)
AS
/*
Figure out if an user has View or Read access permissions on provided Section ID.
*/
SET Transaction Isolation Level Read UNCOMMITTED
BEGIN

DECLARE @HasAllow bit
DECLARE @HasDeny bit
DECLARE @HasAccess bit
 
-- Set default values
SET @HasAllow = 0
SET @HasDeny = 0
SET @HasAccess = 0

-- Has view & read access permission?
IF EXISTS(
	SELECT 1
	FROM
		cs_vw_UsersInRoles ur
		left JOIN cs_SectionPermissions sp on sp.SectionID = @SectionID AND sp.SettingsID = @SettingsID
		left join cs_Sections S on S.SectionID = @SectionID AND S.SettingsID = @SettingsID
		left join cs_ProductPermissions pp on pp.ApplicationType = S.ApplicationType AND pp.SettingsID = @SettingsID
	WHERE
		ur.UserID = @UserID AND 
		(sp.RoleId = ur.RoleId OR pp.RoleId = ur.RoleId) AND
		((sp.AllowMask & convert(bigint, 0x0000000000000001) = convert(bigint, 0x0000000000000001) AND
			sp.AllowMask & convert(bigint, 0x0000000000000002) = convert(bigint, 0x0000000000000002)) OR
		 (pp.AllowMask & convert(bigint, 0x0000000000000001) = convert(bigint, 0x0000000000000001) AND
			pp.AllowMask & convert(bigint, 0x0000000000000002) = convert(bigint, 0x0000000000000002)))
)	
	SET @HasAllow = 1

-- Are they denied at all?
IF EXISTS(
	SELECT 1
	FROM
		cs_vw_UsersInRoles ur
		left JOIN cs_SectionPermissions sp on sp.SectionID = @SectionID AND sp.SettingsID = @SettingsID
		left join cs_Sections S on S.SectionID = @SectionID AND S.SettingsID = @SettingsID
	WHERE
		ur.UserID = @UserID AND 
		sp.RoleId = ur.RoleId AND
		(sp.DenyMask & convert(bigint, 0x0000000000000001) = convert(bigint, 0x0000000000000001) AND
			sp.DenyMask & convert(bigint, 0x0000000000000002) = convert(bigint, 0x0000000000000002))
)	
	SET @HasDeny = 1

IF @HasDeny = 1
	set @HasAccess = 0
else
	set @HasAccess = @HasAllow

RETURN @HasAccess

END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_system_UserCanReadSection] to public


/***********************************************
* Sproc: cs_system_UserIsOnline
* File Date: 11/29/2006 10:07:30 AM
***********************************************/
Print 'Creating...cs_system_UserIsOnline'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_system_UserIsOnline]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_system_UserIsOnline]
GO

CREATE PROCEDURE [dbo].cs_system_UserIsOnline 
(
	@UserID int,
	@LastAction nvarchar(1024),
	@SettingsID int
)
AS
SET Transaction Isolation Level Read UNCOMMITTED
BEGIN

	-- Update cs_Users table
	UPDATE 
		cs_Users 
	SET 
		LastActivity = GetDate(),
		LastAction = @LastAction
	WHERE 
		UserID = @UserID

END


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_system_UserIsOnline] to public
go
/***********************************************
* Sproc: cs_Tags_Get
* File Date: 11/29/2006 10:07:31 AM
***********************************************/
Print 'Creating...cs_Tags_Get'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Tags_Get]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Tags_Get]
GO

CREATE PROCEDURE [dbo].[cs_Tags_Get] 
	@SectionQuerySQL ntext,
	@SettingsID int,
	@CategoryList nvarchar(4000) = null
AS

SET Transaction Isolation Level Read UNCOMMITTED

CREATE TABLE #Sections
(
	SectionID int
)

INSERT INTO #Sections (SectionID)
EXEC (@SectionQuerySQL)

if @CategoryList is null begin

	select [Name], count(*) as TotalCount
	from cs_Post_Categories C
	inner join cs_Posts_InCategories PiC on C.CategoryID = PiC.CategoryID
	where C.SettingsID = @SettingsID
		and C.SectionID in (select SectionID from #Sections)
		and C.IsEnabled = 1
	group by [Name]
	order by [Name]

end else begin

	declare @idoc int
	EXEC sp_xml_preparedocument @idoc OUTPUT, @CategoryList

	CREATE TABLE #Tags
	(
		[Name] nvarchar(255) collate database_default
	)

	insert into #Tags ([Name])
	select CONVERT(nvarchar(255), [text])
	from OPENXML(@idoc, '/Categories/Category/', 2)
	where [text] is not null

	declare @categoryCount int
	set @categoryCount = (select count(*) from #Tags)

	select [Name], count(*) as TotalCount
	from cs_Post_Categories C
	inner join cs_Posts_InCategories PiC on C.CategoryID = PiC.CategoryID
	where C.SettingsID = @SettingsID
		and C.SectionID in (select SectionID from #Sections)
		and C.IsEnabled = 1
		and PiC.PostID in (
			select P2.PostID
			from #Tags X
			inner join cs_Post_Categories C2 on X.[Name] = C2.Name
			inner join cs_Posts_InCategories PiC2 on PiC2.CategoryID = C2.CategoryID
			inner join cs_Posts P2 on PiC2.PostID = P2.PostID
			where C2.SettingsID = @SettingsID
				and C2.SectionID in (select SectionID from #Sections)
				and C2.IsEnabled = 1
				and P2.SettingsID = @SettingsID
				and P2.IsApproved = 1
			group by P2.PostID
			having count(*) = @categoryCount
			)
	group by [Name]
	having [Name] not in (select [Name] from #Tags)
	order by [Name]

	DROP TABLE #Tags

	EXEC sp_xml_removedocument @idoc

end

DROP TABLE #Sections
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT  EXECUTE  ON [dbo].[cs_Tags_Get]  TO [public]
GO


/***********************************************
* Sproc: cs_Threads_GetThreadSet
* File Date: 11/29/2006 10:07:30 AM
***********************************************/
Print 'Creating...cs_Threads_GetThreadSet'

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Threads_GetThreadSet]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Threads_GetThreadSet]
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO



CREATE PROCEDURE [dbo].cs_Threads_GetThreadSet
(
	@SectionID int,
	@PageIndex int, 
	@PageSize int,
	@sqlCount ntext,
	@sqlPopulate ntext,
	@UserID int,
	@SettingsID int,
	@ReturnRecordCount bit,
	@IncludeCategories bit = 0
)
AS

SET Transaction Isolation Level Read UNCOMMITTED
BEGIN

DECLARE @PageLowerBound int
DECLARE @PageUpperBound int
DECLARE @RowsToReturn int
DECLARE @TotalThreads int
DECLARE @GroupID int

-- Set sticky posts unsticky by limiting the scope of the query: the ideea is any user will clean up its stickies when it gets the chance
IF (@SectionID IS NOT NULL AND @SectionID >= 0)
	UPDATE cs_Threads 
	SET StickyDate = ThreadDate, IsSticky = 0 
	WHERE SectionID = @SectionID AND UserID = @UserID AND IsSticky = 1 AND StickyDate < GETDATE() AND SettingsID = @SettingsID
ELSE
	UPDATE cs_Threads 
	SET StickyDate = ThreadDate, IsSticky = 0 
	WHERE UserID = @UserID AND IsSticky = 1 AND StickyDate < GETDATE() AND SettingsID = @SettingsID

-- First set the rowcount
SET @RowsToReturn = @PageSize * (@PageIndex + 1)
SET ROWCOUNT @RowsToReturn

-- Set the page bounds
SET @PageLowerBound = @PageSize * @PageIndex
SET @PageUpperBound = @PageLowerBound + @PageSize + 1


-- Create a temp table to store the select results
CREATE TABLE #PageIndex 
(
	IndexID int IDENTITY (1, 1) NOT NULL,
	ThreadID int
)

INSERT INTO #PageIndex (ThreadID)
EXEC (@sqlPopulate)

SELECT
	jT.*, U.*,
	HasRead = 0,
	jP.PostID,
	jP.Subject,
	jP.Body,
	jP.FormattedBody,
	UserName = jT.PostAuthor,
	jP.PropertyNames as PostPropertyNames, jp.PropertyValues as PostPropertyValues,
	jP.PostConfiguration
FROM 
	#PageIndex jPI
	JOIN cs_Threads jT ON jPI.ThreadID = jT.ThreadID
	JOIN cs_Posts jP ON jPI.ThreadID = jP.ThreadID
	JOIN cs_vw_Users_FullUser U ON jP.UserID = U.cs_UserID and U.SettingsID = @SettingsID
WHERE 
	jPI.IndexID > @PageLowerBound
	AND jPI.IndexID < @PageUpperBound
	AND jP.PostLevel = 1 	-- PostLevel=1 should mean it's a top-level thread starter
ORDER BY
	jPI.IndexID	-- this is the ordering system we're using populated from the @sqlPopulate

SET ROWCOUNT 0

IF @IncludeCategories = 1
BEGIN
	SELECT 
		Cats.[Name], jP.PostID
	FROM 
		#PageIndex jPI
		JOIN cs_Posts jP ON jPI.ThreadID = jP.ThreadID
		JOIN cs_Posts_InCategories PIC ON jP.PostID = PIC.PostID
		JOIN cs_Post_Categories Cats ON PIC.CategoryID = Cats.CategoryID
	WHERE 
		jPI.IndexID > @PageLowerBound
		AND jPI.IndexID < @PageUpperBound
		AND jP.PostLevel = 1 AND jP.SettingsID = @SettingsID
End

-- Update that the user has read this forum
IF @UserID > 0
BEGIN
	IF @SectionID > 0
		EXEC cs_Section_MarkRead @UserID, @SectionID, @SettingsID, @GroupID
END

SET ROWCOUNT @RowsToReturn

-- Do we need to return a record count?
-- *************************************
IF (@ReturnRecordCount = 1)
	EXEC (@sqlCount)

-- Return the users that the message is to if this
-- is a private message
IF @SectionID = 0
	SELECT 
		U.*,
		P2.ThreadID 
	FROM
		cs_PrivateMessages P1, 
		cs_PrivateMessages P2,
		cs_vw_Users_FullUser U
		
	WHERE 
		P1.UserID = @UserID AND 
		P2.UserID <> @UserID AND 
		P2.UserID = U.cs_UserID AND
		P1.ThreadID = P2.ThreadID and U.SettingsID = @SettingsID and P1.SettingsID = @SettingsID and P2.SettingsID = @SettingsID

END
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT  EXECUTE  ON [dbo].[cs_Threads_GetThreadSet]  TO [public]
GO


/***********************************************
* Sproc: cs_Threads_ThreadSet
* File Date: 11/29/2006 10:07:31 AM
***********************************************/
Print 'Creating...cs_Threads_ThreadSet'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Threads_ThreadSet]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Threads_ThreadSet]
GO


Go
/***********************************************
* Sproc: cs_Threads_ThreadSet_Unanswered
* File Date: 11/29/2006 10:07:31 AM
***********************************************/
Print 'Creating...cs_Threads_ThreadSet_Unanswered'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Threads_ThreadSet_Unanswered]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Threads_ThreadSet_Unanswered]
GO




/***********************************************
* Sproc: cs_Thread_Delete
* File Date: 11/29/2006 10:07:33 AM
***********************************************/
Print 'Creating...cs_Thread_Delete'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO


if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Thread_Delete]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Thread_Delete]
GO


CREATE PROCEDURE dbo.cs_Thread_Delete
(
	@SettingsID int,
	@SectionID int,
	@ThreadID int,
	@ResetStatistics bit = 1,
	@DeletedBy INT,
	@Reason NVARCHAR(1024) = ''
)
AS
SET Transaction Isolation Level Read UNCOMMITTED
BEGIN

DECLARE @PostID INT
DECLARE @PostSubject NVARCHAR(256)

SET @PostID = 0
SET @PostSubject = ''

-- Get thread starter's post ID and subject
SELECT
	@PostID = p.PostID,
	@PostSubject = p.Subject
FROM
	cs_Threads t 
	LEFT JOIN cs_Posts AS p 
	ON t.ThreadID = p.ThreadID AND p.PostLevel = 1
WHERE
	t.ThreadID = @ThreadID AND 
	t.SectionID = @SectionID AND
	t.SettingsID = @SettingsID

DELETE FROM cs_PostAttachments WHERE PostID IN (SELECT PostID FROM cs_Posts WHERE ThreadID = @ThreadID AND SettingsID = @SettingsID)

DELETE FROM cs_PostEditNotes WHERE PostID IN (SELECT PostID FROM cs_Posts WHERE ThreadID = @ThreadID AND SettingsID = @SettingsID)

DELETE FROM cs_Posts_InCategories WHERE PostID IN (SELECT PostID FROM cs_Posts WHERE ThreadID = @ThreadID AND SettingsID = @SettingsID)
	
DELETE FROM cs_PostsArchive WHERE PostID IN (SELECT PostID FROM cs_Posts WHERE ThreadID = @ThreadID AND SettingsID = @SettingsID)

DELETE FROM cs_Posts WHERE ThreadID = @ThreadID AND SettingsID = @SettingsID

DELETE FROM cs_ThreadRating WHERE ThreadID = @ThreadID AND SettingsID = @SettingsID

DELETE FROM cs_ThreadsRead WHERE ThreadID = @ThreadID AND SettingsID = @SettingsID

DELETE FROM cs_TrackedThreads WHERE ThreadID = @ThreadID AND SettingsID = @SettingsID

DELETE FROM cs_SearchBarrel WHERE SectionID = @SectionID AND ThreadID = @ThreadID AND SettingsID = @SettingsID

DELETE FROM cs_Threads WHERE ThreadID = @ThreadID AND SettingsID = @SettingsID

-- Update Moderation Audit table
IF (@PostID IS NOT NULL AND @PostID > 0)
BEGIN
	IF (@Reason IS NULL OR @Reason = '')
		SET @Reason = 'Automatic generated reason: thread starter post has been permanently deleted on request. Thread ID: ' + CAST(@ThreadID AS NVARCHAR(30)) + '. Thread Name: ' + @PostSubject

	EXEC cs_system_ModerationAction_AuditEntry 4, @DeletedBy, @PostID, null, null, @SettingsID, @Reason
END

-- Update forum's statistics?
IF (@ResetStatistics = 1)
BEGIN
	EXEC cs_system_ResetForumStatistics @SectionID

	EXEC cs_Posts_UpdatePostsInCategories @SectionID = @SectionID, @PostID = @PostID
END

END

GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_Thread_Delete] to public
go
/***********************************************
* Sproc: cs_thread_IsTracked
* File Date: 11/29/2006 10:07:31 AM
***********************************************/
Print 'Creating...cs_thread_IsTracked'

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_thread_IsTracked]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_thread_IsTracked]
GO



CREATE  PROCEDURE [dbo].cs_thread_IsTracked
(
	@SettingsID int,
	@ThreadID int,
	@UserID int,
	@IsTracked bit output
)
AS
SET Transaction Isolation Level Read UNCOMMITTED
BEGIN

IF EXISTS(SELECT ThreadID FROM cs_TrackedThreads (nolock) WHERE ThreadID = @ThreadID AND UserID=@UserID and SettingsID = @SettingsID)
	SELECT @IsTracked = 1
ELSE
	SELECT @IsTracked = 0

END























GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_thread_IsTracked] to public
go
/***********************************************
* Sproc: cs_Thread_Next
* File Date: 11/29/2006 10:07:30 AM
***********************************************/
Print 'Creating...cs_Thread_Next'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Thread_Next]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Thread_Next]
GO

/***********************************************
* Sproc: cs_Thread_Previous
* File Date: 11/29/2006 10:07:31 AM
***********************************************/
Print 'Creating...cs_Thread_Previous'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Thread_Previous]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Thread_Previous]
GO

/***********************************************
* Sproc: cs_Thread_PrevNext
* File Date: 11/29/2006 10:07:34 AM
***********************************************/
Print 'Creating...cs_Thread_PrevNext'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Thread_PrevNext]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Thread_PrevNext]
GO



CREATE procedure [dbo].cs_Thread_PrevNext
(
	@PostID int,
	@NavigationType int,
	@SettingsID int
)
AS

DECLARE @ThreadDate datetime
DECLARE	@SectionID int
DECLARE	@ThreadID int


-- Get thread info
SELECT
	@ThreadDate = T.StickyDate,
	@SectionID = T.SectionID
FROM
	cs_Threads T INNER JOIN cs_Posts P ON T.ThreadID = P.ThreadID
WHERE
	P.PostID = @PostID AND
	P.SettingsID = @SettingsID


-- Compute prev/next thread
IF @NavigationType = 1	-- previous thread
BEGIN
	SELECT TOP 1
		@ThreadID = T.MostRecentPostID
	FROM
		cs_Threads T
	WHERE
		T.SectionID = @SectionID AND
		T.IsApproved = 1 AND
		StickyDate < @ThreadDate AND
		T.SettingsID = @SettingsID
	ORDER BY
		IsSticky DESC,
		StickyDate DESC

	IF @@ROWCOUNT < 1
	BEGIN
		-- reached the beginning, no previous, so find last thread
		SELECT TOP 1
			@ThreadID = T.MostRecentPostID
		FROM
			cs_Threads T
		WHERE
			T.SectionID = @SectionID AND
			T.IsApproved = 1 AND
			T.SettingsID = @SettingsID
		ORDER BY
			IsSticky DESC,
			StickyDate DESC

		-- no threads exist
		IF @@ROWCOUNT < 1
			SET @ThreadID = 0
	END
END
ELSE IF @NavigationType = 0	-- next thread
BEGIN
	SELECT TOP 1
		@ThreadID = T.MostRecentPostID
	FROM
		cs_Threads T
	WHERE
		T.SectionID = @SectionID AND
		T.IsApproved = 1 AND
		StickyDate > @ThreadDate AND
		T.SettingsID = @SettingsID
	ORDER BY
		IsSticky ASC,
		StickyDate ASC

	IF @@ROWCOUNT < 1
	BEGIN
		-- reached the end, no next, so find first thread
		SELECT TOP 1
			@ThreadID = T.MostRecentPostID
		FROM
			cs_Threads T
		WHERE
			T.SectionID = @SectionID AND
			T.IsApproved = 1 AND
			T.SettingsID = @SettingsID
		ORDER BY
			IsSticky ASC,
			StickyDate ASC

		-- no threads exist
		IF @@ROWCOUNT < 1
			SET @ThreadID = 0
	END
END

SELECT ThreadID = @ThreadID
GO


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_Thread_PrevNext] to public
go
/***********************************************
* Sproc: cs_Thread_Rate
* File Date: 11/29/2006 10:07:31 AM
***********************************************/
Print 'Creating...cs_Thread_Rate'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Thread_Rate]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Thread_Rate]
GO

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

/***********************************************
* Sproc: cs_Thread_Rate_Get
* File Date: 11/29/2006 10:07:33 AM
***********************************************/
Print 'Creating...cs_Thread_Rate_Get'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Thread_Rate_Get]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Thread_Rate_Get]
GO

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

/***********************************************
* Sproc: cs_Thread_Status_Update
* File Date: 11/29/2006 10:07:31 AM
***********************************************/
Print 'Creating...cs_Thread_Status_Update'

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Thread_Status_Update]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Thread_Status_Update]
GO


CREATE PROCEDURE [dbo].cs_Thread_Status_Update 
(
	@ThreadID int,
	@Status int = null,
	@SettingsID int
)
AS
SET Transaction Isolation Level Read UNCOMMITTED

IF @Status IS NOT NULL
BEGIN

	UPDATE
		cs_Threads
	SET
		ThreadStatus = @Status
	WHERE
		ThreadID = @ThreadID AND SettingsID = @SettingsID

END
ELSE
BEGIN

	IF EXISTS (SELECT * FROM cs_Posts WHERE ThreadID = @ThreadID AND (PostStatus & 64) = 64)
		SET @Status = 1	-- if at least one reply is marked as an answer, mark the thread as answered
	ELSE
		SET @Status = 2	-- otherwise, mark the thread as unanswered

	UPDATE
		cs_Threads
	SET
		ThreadStatus = @Status
	WHERE
		ThreadID = @ThreadID AND SettingsID = @SettingsID

END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

grant execute on [dbo].[cs_Thread_Status_Update] to public
go
/***********************************************
* Sproc: cs_UpdateForumGroupSortOrder
* File Date: 11/29/2006 10:07:31 AM
***********************************************/
Print 'Creating...cs_UpdateForumGroupSortOrder'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_UpdateForumGroupSortOrder]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_UpdateForumGroupSortOrder]
GO
/***********************************************
* Sproc: cs_UrlRedirects_Get
* File Date: 11/29/2006 10:07:31 AM
***********************************************/
Print 'Creating...cs_UrlRedirects_Get'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_UrlRedirects_Get]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_UrlRedirects_Get]
GO


CREATE proc [dbo].[cs_UrlRedirects_Get]
(
	@UrlID	int = 0
)
as
SET Transaction Isolation Level Read UNCOMMITTED
	select
		UrlID, Url, Description, Impressions
	from
		cs_UrlRedirects
	where
		UrlID = @UrlID OR (@UrlID = 0)
	order by
		UrlID

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_UrlRedirects_Get] to public
go

/***********************************************
* Sproc: cs_UrlRedirect_CreateUpdateDelete
* File Date: 11/29/2006 10:07:30 AM
***********************************************/
Print 'Creating...cs_UrlRedirect_CreateUpdateDelete'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_UrlRedirect_CreateUpdateDelete]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_UrlRedirect_CreateUpdateDelete]
GO


CREATE proc [dbo].[cs_UrlRedirect_CreateUpdateDelete]
(
	@UrlID			int out,
	@Url			nvarchar(4000),
	@Description	nvarchar(2000),
	@Action 		int
)
as
SET Transaction Isolation Level Read UNCOMMITTED
SET NOCOUNT ON

--Create
IF @Action = 0
BEGIN
	INSERT INTO
		cs_UrlRedirects (Url, Description)
	VALUES
		(@Url, @Description)

	SET @UrlID = @@IDENTITY
END
--Update
ELSE IF @Action = 1
BEGIN
	UPDATE cs_UrlRedirects SET
		Description = @Description,
		Url = @Url
	WHERE
		UrlID = @UrlID
END
--Delete
ELSE IF @Action = 2
BEGIN
	DELETE FROM
		cs_UrlRedirects
	WHERE
		UrlID = @UrlID
	RETURN
END


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT EXECUTE on [dbo].[cs_UrlRedirect_CreateUpdateDelete] to public
GO
/***********************************************
* Sproc: cs_Urls_Add
* File Date: 11/29/2006 10:07:33 AM
***********************************************/
Print 'Creating...cs_Urls_Add'


if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Urls_Add]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Urls_Add]

Go

Create Proc [dbo].cs_Urls_Add
(
	@UrlID int,
	@Url nvarchar(512)
)

as 
SET Transaction Isolation Level Read UNCOMMITTED

if not exists (Select UrlID From cs_urls where UrlID = @UrlID)
Begin
	Insert cs_Urls (UrlID, Url) values (@UrlID, @Url)
End
go



grant execute on [dbo].[cs_Urls_Add] to public
go


/***********************************************
* Sproc: cs_Urls_RedirectLookup
* File Date: 11/29/2006 10:07:32 AM
***********************************************/
Print 'Creating...cs_Urls_RedirectLookup'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Urls_RedirectLookup]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Urls_RedirectLookup]
GO


create procedure [dbo].[cs_Urls_RedirectLookup]
    @UrlID        int
as
BEGIN
	SELECT 
		url
	FROM
		cs_UrlRedirects
	WHERE
		urlID = @UrlID


	UPDATE
		cs_UrlRedirects
	SET
		impressions = impressions + 1
	WHERE
		urlID = @UrlID
END


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_Urls_RedirectLookup] to public
go
/***********************************************
* Sproc: cs_UserActivityNightlyJob
* File Date: 11/29/2006 10:07:31 AM
***********************************************/
Print 'Creating...cs_UserActivityNightlyJob'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_UserActivityNightlyJob]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_UserActivityNightlyJob]
GO

CREATE     PROCEDURE [dbo].cs_UserActivityNightlyJob

AS
SET Transaction Isolation Level Read UNCOMMITTED
BEGIN
	declare @RangeDate datetime
	declare @JobRunDate datetime
	set @JobRunDate = getdate()
	set @RangeDate = dateadd(d, -1, convert(datetime, (convert(varchar(10), @JobRunDate, 101))))
	
	insert into [cs_VisitsDaily]
	select
		v.IP
		,VisitCount  = (select sum(v1.VisitCount) from cs_Visits v1 where (v1.IP = v.IP) and (v1.DateTimeStamp between @RangeDate and dateadd(d, 1, @RangeDate)) group by v1.IP)
		,VisitDate = @RangeDate
		,JobDate = @JobRunDate
	from
		cs_Visits v
	where
		v.DateTimeStamp between @RangeDate and dateadd(d, 1, @RangeDate)
	group by
		v.IP

	---------------------------------------------
	
	DELETE cs_Visits WHERE cs_Visits.DateTimeStamp between @RangeDate and dateadd(d, 1, @RangeDate)
END



GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].cs_UserActivityNightlyJob to public
go

/***********************************************
* Sproc: cs_UserActivityReportRecords_Get
* File Date: 11/29/2006 10:07:31 AM
***********************************************/
Print 'Creating...cs_UserActivityReportRecords_Get'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_UserActivityReportRecords_Get]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_UserActivityReportRecords_Get]
GO

CREATE      PROCEDURE [dbo].cs_UserActivityReportRecords_Get
(
	 @nRecordNumberStart INT
    	,@nRecordNumberEnd INT
        ,@BegReportDate DateTime
	,@EndReportDate DateTime
	,@Paged BIT
)
AS
BEGIN
IF @Paged = 1
	BEGIN
		DECLARE @totalRecords INT
	
		--------------------------------------------------------------------
	    	-- Define the table to do the filtering and paging
	    	--------------------------------------------------------------------
	    	DECLARE @tblTempData TABLE
	        (
	        	nID INT IDENTITY
	        	,IP nvarchar(20)
	        	,VisitCount INT
	        )
		INSERT INTO @tblTempData
		(
	        	IP
	        	,VisitCount
	        )
	    	SELECT  IP, SUM(VisitCount) as VisitCount
		FROM     cs_VisitsDaily AS v
		WHERE 
			v.VisitDate between @BegReportDate and @EndReportDate
		GROUP BY
			v.IP
		ORDER BY
			VisitCount DESC
		SET @totalRecords = @@rowcount
	        ---------------------------------------------------------------------------------------------------------------------------------------
		SELECT
	        	IP
	        	,VisitCount
	    	FROM
			@tblTempData 
	    	WHERE
			nID BETWEEN @nRecordNumberStart AND @nRecordNumberEnd
	    	ORDER BY 
	        	nID ASC
	
		-- Return totalRecords
		SELECT @totalRecords
	END
ELSE
	BEGIN
		SELECT  IP as IP_Address, SUM(VisitCount) as Number_Page_Visits
		FROM     cs_VisitsDaily AS v
		WHERE 
			v.VisitDate between @BegReportDate and @EndReportDate
		GROUP BY
			v.IP
		ORDER BY
			Number_Page_Visits DESC
	END
END




GO


SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_UserActivityReportRecords_Get] to public
go

/***********************************************
* Sproc: cs_UserFeed_DeleteFeed
* File Date: 11/29/2006 10:07:29 AM
***********************************************/
Print 'Creating...cs_UserFeed_DeleteFeed'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_UserFeed_DeleteFeed]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_UserFeed_DeleteFeed]
GO


CREATE PROC [dbo].cs_UserFeed_DeleteFeed
 @UserId INT,  
 @FeedId INT,
 @SettingsID INT  
AS  
  
DELETE  
FROM cs_UserReadPost  
WHERE UserId = @UserId  
  AND FeedPostId IN (SELECT FeedPostId FROM cs_FeedPost WHERE FeedId = @FeedId)  
  
DELETE  
FROM cs_FolderFeed  
WHERE FolderFeedId IN (
  SELECT FolderFeedId
  FROM cs_FolderFeed
  WHERE UserId = @UserId
    AND FeedId = @FeedId
) 



if not exists(Select FolderFeedId FROM cs_FolderFeed where FeedId = @FeedID and SettingsID = @SettingsID)
BEGIN
	Delete FROM cs_FeedPost where FeedID = @FeedID
	Delete FROM cs_Feed where FeedID = @FeedId
END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT EXECUTE ON [dbo].cs_UserFeed_DeleteFeed  TO PUBLIC
GO

/***********************************************
* Sproc: cs_UserHasPostsAwaitingModeration
* File Date: 11/29/2006 10:07:31 AM
***********************************************/
Print 'Creating...cs_UserHasPostsAwaitingModeration'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_UserHasPostsAwaitingModeration]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_UserHasPostsAwaitingModeration]
GO


create  procedure [dbo].cs_UserHasPostsAwaitingModeration
(
	@UserName nvarchar(50),
	@SettingsID int
)
AS
SET Transaction Isolation Level Read UNCOMMITTED
BEGIN
	-- Can the user moderate all forums?
	IF EXISTS(SELECT NULL FROM Moderators (nolock) WHERE UserName=@UserName AND SectionID=0)

		-- return ALL posts awaiting moderation
		IF EXISTS(SELECT TOP 1 PostID FROM Posts P (nolock) INNER JOIN Forums F (nolock) ON F.SectionID = P.SectionID WHERE Approved = 0 and SettingsID = @SettingsID)
		  SELECT 1
		ELSE
		  SELECT 0
	ELSE
		-- return only those posts in the forum this user can moderate
		IF EXISTS (SELECT TOP 1 PostID FROM Posts P (nolock) INNER JOIN Forums F (nolock) ON F.SectionID = P.SectionID WHERE Approved = 0 AND P.SectionID IN (SELECT SectionID FROM Moderators (nolock) WHERE UserName=@UserName and SettingsID = @SettingsID)  and F.SettingsID = @SettingsID)
		  SELECT 1
		ELSE
		  SELECT 0
	
END



GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_UserHasPostsAwaitingModeration] to public
go
/***********************************************
* Sproc: cs_UserInvitations_Expire
* File Date: 11/29/2006 10:07:34 AM
***********************************************/
Print 'Creating...cs_UserInvitations_Expire'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_UserInvitations_Expire]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_UserInvitations_Expire]
GO

CREATE PROCEDURE [dbo].cs_UserInvitations_Expire
	@DateInvited datetime
AS

delete from cs_UserInvitation
where DateInvited < @DateInvited
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT  EXECUTE  ON [dbo].[cs_UserInvitations_Expire]  TO [public]
GO


/***********************************************
* Sproc: cs_UserInvitations_GetBeforeDate
* File Date: 11/29/2006 10:07:31 AM
***********************************************/
Print 'Creating...cs_UserInvitations_GetBeforeDate'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_UserInvitations_GetBeforeDate]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_UserInvitations_GetBeforeDate]
GO

CREATE PROCEDURE [dbo].cs_UserInvitations_GetBeforeDate
	@DateInvited datetime
AS

SET Transaction Isolation Level Read UNCOMMITTED
BEGIN

select InvitationKey, UserID, Email, DateInvited, PropertyNames, PropertyValues
from cs_UserInvitation
where DateInvited < @DateInvited
order by DateInvited

END
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT  EXECUTE  ON [dbo].[cs_UserInvitations_GetBeforeDate]  TO [public]
GO


/***********************************************
* Sproc: cs_UserInvitations_GetByUser
* File Date: 11/29/2006 10:07:31 AM
***********************************************/
Print 'Creating...cs_UserInvitations_GetByUser'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_UserInvitations_GetByUser]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_UserInvitations_GetByUser]
GO


CREATE PROCEDURE [dbo].cs_UserInvitations_GetByUser
	@UserID int
AS

SET Transaction Isolation Level Read UNCOMMITTED
BEGIN

select InvitationKey, UserID, Email, DateInvited, PropertyNames, PropertyValues
from cs_UserInvitation
where UserID = @UserID
order by DateInvited

END
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_UserInvitations_GetByUser] to public
go

/***********************************************
* Sproc: cs_UserInvitation_Create
* File Date: 11/29/2006 10:07:32 AM
***********************************************/
Print 'Creating...cs_UserInvitation_Create'

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_UserInvitation_Create]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_UserInvitation_Create]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO



CREATE PROCEDURE [dbo].cs_UserInvitation_Create
	@UserID int,
	@Email nvarchar(255),
	@DateInvited datetime,
	@PropertyNames ntext = null,
	@PropertyValues ntext = null,
	@InvitationKey uniqueidentifier out
AS

set @InvitationKey = newid()

insert into cs_UserInvitation (InvitationKey, UserID, Email, DateInvited, PropertyNames, PropertyValues)
values (@InvitationKey, @UserID, @Email, @DateInvited, @PropertyNames, @PropertyValues)
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT  EXECUTE  ON [dbo].[cs_UserInvitation_Create]  TO [public]
GO


/***********************************************
* Sproc: cs_UserInvitation_Delete
* File Date: 11/29/2006 10:07:31 AM
***********************************************/
Print 'Creating...cs_UserInvitation_Delete'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_UserInvitation_Delete]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_UserInvitation_Delete]
GO

CREATE PROCEDURE [dbo].cs_UserInvitation_Delete
	@InvitationKey uniqueidentifier
AS

delete from cs_UserInvitation
where InvitationKey = @InvitationKey
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT  EXECUTE  ON [dbo].[cs_UserInvitation_Delete]  TO [public]
GO


/***********************************************
* Sproc: cs_UserInvitation_Get
* File Date: 11/29/2006 10:07:30 AM
***********************************************/
Print 'Creating...cs_UserInvitation_Get'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_UserInvitation_Get]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_UserInvitation_Get]
GO

CREATE PROCEDURE [dbo].cs_UserInvitation_Get
	@InvitationKey uniqueidentifier
AS

SET Transaction Isolation Level Read UNCOMMITTED
BEGIN

select InvitationKey, UserID, Email, DateInvited, PropertyNames, PropertyValues
from cs_UserInvitation
where InvitationKey = @InvitationKey

END
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT  EXECUTE  ON [dbo].[cs_UserInvitation_Get]  TO [public]
GO


/***********************************************
* Sproc: cs_UserPoints_Add
* File Date: 11/29/2006 10:07:32 AM
***********************************************/
Print 'Creating...cs_UserPoints_Add'

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_UserPoints_Add]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_UserPoints_Add]
GO

/***********************************************
* Sproc: cs_UserReadPost_MarkPostRead
* File Date: 11/29/2006 10:07:34 AM
***********************************************/
Print 'Creating...cs_UserReadPost_MarkPostRead'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_UserReadPost_MarkPostRead]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_UserReadPost_MarkPostRead]
GO


CREATE PROC [dbo].cs_UserReadPost_MarkPostRead
	@UserId INT,
	@FeedPostId INT
AS

INSERT INTO cs_UserReadPost
(
	UserId,
	FeedPostId
)
VALUES
(
	@UserId,
	@FeedPostId
)


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT EXECUTE ON [dbo].cs_UserReadPost_MarkPostRead  TO PUBLIC
GO

/***********************************************
* Sproc: cs_users_BackPort
* File Date: 11/29/2006 10:07:32 AM
***********************************************/
Print 'Creating...cs_users_BackPort'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_users_BackPort]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_users_BackPort]
GO




CREATE proc [dbo].cs_users_BackPort
(
	@SettingsID int,
	@UserName nvarchar(256),
	@Password nvarchar(128) = null,
	@PasswordSalt nvarchar(128) = null,
	@PasswordFormat int = null
)
as
SET Transaction Isolation Level Read UNCOMMITTED
if(@Password is null)
Begin
	Select a.Password, a.PasswordSalt, a.PasswordFormat  FROM cs_vw_Users_FullUser c, aspnet_Membership a where a.UserId = c.UserId and SettingsID = @SettingsID and @UserName = UserName
End
Else
Begin
	Declare @UserID uniqueidentifier
	Select @UserID = UserId FROM cs_vw_Users_FullUser where UserName = @UserName and SettingsID = @SettingsID
	
	Update aspnet_Membership
	Set Password = @Password, PasswordSalt = @PasswordSalt, PasswordFormat = @PasswordFormat
	Where UserId = @UserID
		
End

go


grant execute on [dbo].[cs_users_BackPort] to public
go
/***********************************************
* Sproc: cs_users_count_Get
* File Date: 11/29/2006 10:07:31 AM
***********************************************/
Print 'Creating...cs_users_count_Get'

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_users_count_Get]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_users_count_Get]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO




--cs_users_count_Get 0, 10, 0, 0, null, 0, 1, 0, 0, 1000
CREATE          PROCEDURE [dbo].cs_users_count_Get
(
	@UsernameFilter nvarchar(128),
	@FilterIncludesEmailAddress bit = 0,
	@UserAccountStatus smallint = 1,
	@IncludeHiddenUsers bit = 0,
	@SettingsID int
)
AS

SET Transaction Isolation Level Read UNCOMMITTED

Declare @TotalUsers int

BEGIN

-- Do we need to return a record count?
-- *************************************
  IF ((@UsernameFilter IS NULL) OR (@UsernameFilter = ''))
    SET @TotalUsers = (SELECT count(cs_UserID) FROM cs_vw_Users_FullUser where SettingsID = @SettingsID and  (cs_UserAccountStatus = @UserAccountStatus OR @UserAccountStatus = 9999) AND (EnableDisplayInMemberList = 1 or @IncludeHiddenUsers = 1))
  ELSE
    IF (@FilterIncludesEmailAddress = 0)
      SET @TotalUsers = (SELECT count(cs_UserID) FROM cs_vw_Users_FullUser where SettingsID = @SettingsID and  (cs_UserAccountStatus = @UserAccountStatus OR @UserAccountStatus = 9999) AND (EnableDisplayInMemberList = 1 or @IncludeHiddenUsers = 1) AND UserName LIKE @UsernameFilter)
    ELSE
      SET @TotalUsers = (SELECT count(cs_UserID) FROM cs_vw_Users_FullUser where SettingsID = @SettingsID and  (cs_UserAccountStatus = @UserAccountStatus OR @UserAccountStatus = 9999) AND (EnableDisplayInMemberList = 1 or @IncludeHiddenUsers = 1) AND (UserName LIKE @UsernameFilter OR Email LIKE @UsernameFilter))



END




  SELECT @TotalUsers
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT  EXECUTE  ON [dbo].[cs_users_count_Get]  TO [public]
GO


/***********************************************
* Sproc: cs_users_Get
* File Date: 11/29/2006 10:07:31 AM
***********************************************/
Print 'Creating...cs_users_Get'

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_users_Get]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_users_Get]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO



CREATE PROCEDURE [dbo].cs_users_Get
(
	@PageIndex int,
	@PageSize int,
	@sqlPopulate ntext,
	@SearchText nvarchar(256),
	@ReturnModerationCounters bit = 0,
	@SettingsID int
)
AS

SET Transaction Isolation Level Read UNCOMMITTED

BEGIN
DECLARE @PageLowerBound int
DECLARE @PageUpperBound int
DECLARE @RowsToReturn int
DECLARE @TotalUsers int

-- Set the page bounds
SET @PageLowerBound = @PageSize * @PageIndex
SET @PageUpperBound = @PageLowerBound + @PageSize + 1

-- First set the rowcount
--SET @RowsToReturn = @PageSize * (@PageIndex + 1)
--SET ROWCOUNT @RowsToReturn

-- Create a temp table to store the select results
CREATE TABLE #PageIndexForUsers 
(
	IndexID int IDENTITY (1, 1) NOT NULL,
	UserID int
)	

DECLARE @ParmDefinition NVARCHAR(500)
SET @ParmDefinition = N'@SearchText nvarchar(256)'

INSERT INTO #PageIndexForUsers (UserID)
Exec sp_executesql @sqlPopulate, @ParmDefinition, @SearchText



SET @TotalUsers = @@rowcount

-- Get the user details
IF @ReturnModerationCounters = 1
	SELECT
		U.*,
		ApprovePost = (SELECT COUNT(*) FROM cs_ModerationAudit WHERE ModerationAction = 1 AND UserID = U.cs_UserID AND SettingsID = @SettingsID),
		EditPost = (SELECT COUNT(*) FROM cs_ModerationAudit WHERE ModerationAction = 2 AND UserID = U.cs_UserID AND SettingsID = @SettingsID),
		MovePost = (SELECT COUNT(*) FROM cs_ModerationAudit WHERE ModerationAction = 3 AND UserID = U.cs_UserID AND SettingsID = @SettingsID),
		DeletePost = (SELECT COUNT(*) FROM cs_ModerationAudit WHERE ModerationAction = 4 AND UserID = U.cs_UserID AND SettingsID = @SettingsID),
		LockPost = (SELECT COUNT(*) FROM cs_ModerationAudit WHERE ModerationAction = 5 AND UserID = U.cs_UserID AND SettingsID = @SettingsID),
		UnlockPost = (SELECT COUNT(*) FROM cs_ModerationAudit WHERE ModerationAction = 6 AND UserID = U.cs_UserID AND SettingsID = @SettingsID),
		MergePost = (SELECT COUNT(*) FROM cs_ModerationAudit WHERE ModerationAction = 7 AND UserID = U.cs_UserID AND SettingsID = @SettingsID),
		SplitPost = (SELECT COUNT(*) FROM cs_ModerationAudit WHERE ModerationAction = 8 AND UserID = U.cs_UserID AND SettingsID = @SettingsID),
		EditUser = (SELECT COUNT(*) FROM cs_ModerationAudit WHERE ModerationAction = 9 AND UserID = U.cs_UserID AND SettingsID = @SettingsID),
		UnmoderateUser = (SELECT COUNT(*) FROM cs_ModerationAudit WHERE ModerationAction = 10 AND UserID = U.cs_UserID AND SettingsID = @SettingsID),
		ModerateUser = (SELECT COUNT(*) FROM cs_ModerationAudit WHERE ModerationAction = 11 AND UserID = U.cs_UserID AND SettingsID = @SettingsID),
		BanUser = (SELECT COUNT(*) FROM cs_ModerationAudit WHERE ModerationAction = 12 AND UserID = U.cs_UserID AND SettingsID = @SettingsID),
		UnbanUser = (SELECT COUNT(*) FROM cs_ModerationAudit WHERE ModerationAction = 13  AND UserID = U.cs_UserID AND SettingsID = @SettingsID),
		ResetPassword = (SELECT COUNT(*) FROM cs_ModerationAudit WHERE ModerationAction = 14  AND UserID = U.cs_UserID AND SettingsID = @SettingsID),
		ChangePassword = (SELECT COUNT(*) FROM cs_ModerationAudit WHERE ModerationAction = 15  AND UserID = U.cs_UserID AND SettingsID = @SettingsID),
		PostIsAnnouncement = (SELECT COUNT(*) FROM cs_ModerationAudit WHERE ModerationAction = 16  AND UserID = U.cs_UserID AND SettingsID = @SettingsID),
		PostIsNotAnnoucement = (SELECT COUNT(*) FROM cs_ModerationAudit WHERE ModerationAction = 17  AND UserID = U.cs_UserID AND SettingsID = @SettingsID),
		UnApprovePost = (SELECT COUNT(*) FROM cs_ModerationAudit WHERE ModerationAction = 18  AND UserID = U.cs_UserID AND SettingsID = @SettingsID)	
		-- (we do not see to be using this value),IsModerator = (SELECT Count(*) FROM cs_Moderators WHERE UserID = U.cs_UserID)
	FROM 
		cs_vw_Users_FullUser U (nolock),
		#PageIndexForUsers
	WHERE 
		U.cs_UserID = #PageIndexForUsers.UserID AND
		#PageIndexForUsers.IndexID > @PageLowerBound AND
		#PageIndexForUsers.IndexID < @PageUpperBound and U.SettingsID = @SettingsID
	ORDER BY
		#PageIndexForUsers.IndexID
ELSE
	SELECT
		U.*
		-- (we do not see to be using this value),IsModerator = (SELECT Count(*) FROM cs_Moderators WHERE UserID = U.cs_UserID)
	FROM 
		cs_vw_Users_FullUser U (nolock),
		#PageIndexForUsers
	WHERE 
		U.cs_UserID = #PageIndexForUsers.UserID AND
		#PageIndexForUsers.IndexID > @PageLowerBound AND
		#PageIndexForUsers.IndexID < @PageUpperBound and U.SettingsID = @SettingsID
	ORDER BY
		#PageIndexForUsers.IndexID

END

-- Return the record count
SELECT @TotalUsers

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT  EXECUTE  ON [dbo].[cs_users_Get]  TO [public]
GO


/***********************************************
* Sproc: cs_Users_GetUserIDByFilter
* File Date: 11/29/2006 10:07:31 AM
***********************************************/
Print 'Creating...cs_Users_GetUserIDByFilter'

SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS ON
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Users_GetUserIDByFilter]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Users_GetUserIDByFilter]
GO
--------------------------------------------------------------------------------
--	cs_Users_GetUserIDByFilter
--	Returns a list of filtered UserIDs
--------------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[cs_Users_GetUserIDByFilter]
(
	@SettingsID		int,
	@FilterType		int,
	@FilterValue	varchar(255)
)
AS
	SET NOCOUNT ON
	SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED


	-- local variables
	DECLARE	@UserSetSize	int


	IF @FilterType = 1	-- StalePoints
	BEGIN

		-- filter value represent size of user set
		SET @UserSetSize = CONVERT(int, @FilterValue)

		-- limit number of users to work with (non-positive = ALL)
		IF @UserSetSize > 0
			SET ROWCOUNT @UserSetSize

		-- get posts to work with
		SELECT		UP.UserID
		FROM		cs_UserProfile UP
		WHERE		UP.SettingsID = @SettingsID
		ORDER BY	UP.PointsUpdated			-- start with "stalest" users

		-- limit has been used; reset to default
		IF @UserSetSize > 0
			SET ROWCOUNT 0
	END


	RETURN
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO

GRANT EXECUTE on [dbo].[cs_Users_GetUserIDByFilter] to [public]

/***********************************************
* Sproc: cs_users_Online
* File Date: 11/29/2006 10:07:33 AM
***********************************************/
Print 'Creating...cs_users_Online'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_users_Online]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_users_Online]
GO


CREATE PROCEDURE [dbo].cs_users_Online
(
	@PastMinutes int,
	@SettingsID int
)
AS
SET Transaction Isolation Level Read UNCOMMITTED
BEGIN

	-- Get users 
	SELECT
		U.*
	FROM
		cs_vw_Users_FullUser U
	WHERE
		U.IsAnonymous = 0 AND
		U.cs_LastActivity  > DateAdd(minute, -@PastMinutes, GetDate()) AND
		U.SettingsID = @SettingsID
	ORDER BY U.UserName
	
	-- Get anonymous 
	SELECT
		UserID,
		LastActivity = LastLogin,
		LastAction
	FROM
		cs_AnonymousUsers where SettingsID = @SettingsID

END


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_users_Online] to public
go
/***********************************************
* Sproc: cs_users_UsersInRole_Get
* File Date: 11/29/2006 10:07:30 AM
***********************************************/
Print 'Creating...cs_users_UsersInRole_Get'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_users_UsersInRole_Get]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_users_UsersInRole_Get]
GO


CREATE PROCEDURE [dbo].cs_users_UsersInRole_Get
(
	@PageIndex int,
	@PageSize int,
	@SortBy int = 0,
	@SortOrder int = 0,
	@RoleID uniqueidentifier,
	@UserAccountStatus smallint = 1,
	@ReturnRecordCount bit = 0,
	@SettingsID int
)
AS
BEGIN
DECLARE @PageLowerBound int
DECLARE @PageUpperBound int
DECLARE @RowsToReturn int
DECLARE @TotalUsers int

-- Set the page bounds
SET @PageLowerBound = @PageSize * @PageIndex
SET @PageUpperBound = @PageLowerBound + @PageSize + 1

-- First set the rowcount
SET @RowsToReturn = @PageSize * (@PageIndex + 1)
SET ROWCOUNT @RowsToReturn

-- Create a temp table to store the select results
CREATE TABLE #PageIndexForUsers 
(
	IndexID int IDENTITY (1, 1) NOT NULL,
	UserID int
)	

-- Do we need to return a record count?
-- *************************************
IF (@ReturnRecordCount = 1)
    SET @TotalUsers = (SELECT count(*) FROM cs_vw_Users_FullUser U, aspnet_UsersInRoles R WHERE R.UserId = U.UserId AND U.cs_UserAccountStatus = @UserAccountStatus AND EnableDisplayInMemberList = 1 AND RoleId = @RoleID and U.SettingsID = @SettingsID)

-- Special case depending on what the user wants and how they want it ordered by
-- *************************************

-- Sort by Date Joined
IF @SortBy = 0 AND @SortOrder = 1
    INSERT INTO #PageIndexForUsers (UserID)
    SELECT U.cs_UserID FROM cs_vw_Users_FullUser U, aspnet_UsersInRoles R WHERE R.UserID = U.UserID AND U.cs_UserAccountStatus = @UserAccountStatus AND EnableDisplayInMemberList = 1 AND RoleID = @RoleID and U.SettingsID = @SettingsID ORDER BY CreateDate
ELSE IF @SortBy = 0 AND @SortOrder = 0
    INSERT INTO #PageIndexForUsers (UserID)
    SELECT U.cs_UserID FROM cs_vw_Users_FullUser U, aspnet_UsersInRoles R WHERE R.UserID = U.UserID AND U.cs_UserAccountStatus = @UserAccountStatus AND EnableDisplayInMemberList = 1 AND RoleID = @RoleID and U.SettingsID = @SettingsID  ORDER BY CreateDate DESC

-- Sort by username
IF @SortBy = 1 AND @SortOrder = 1
	INSERT INTO #PageIndexForUsers (UserID)
    SELECT U.cs_UserID FROM cs_vw_Users_FullUser U, aspnet_UsersInRoles R WHERE R.UserID = U.UserID AND U.cs_UserAccountStatus = @UserAccountStatus AND EnableDisplayInMemberList = 1 AND RoleID = @RoleID and U.SettingsID = @SettingsID  ORDER BY UserName DESC
ELSE IF @SortBy = 1 AND @SortOrder = 0
	INSERT INTO #PageIndexForUsers (UserID)
    SELECT U.cs_UserID FROM cs_vw_Users_FullUser U, aspnet_UsersInRoles R WHERE R.UserID = U.UserID AND U.cs_UserAccountStatus = @UserAccountStatus AND EnableDisplayInMemberList = 1 AND RoleID = @RoleID and U.SettingsID = @SettingsID  ORDER BY UserName

-- Sort by Last Active
IF @SortBy = 3 AND @SortOrder = 1
    INSERT INTO #PageIndexForUsers (UserID)
    SELECT U.cs_UserID FROM cs_vw_Users_FullUser U, aspnet_UsersInRoles R WHERE R.UserID = U.UserID AND U.cs_UserAccountStatus = @UserAccountStatus AND EnableDisplayInMemberList = 1 AND RoleID = @RoleID and U.SettingsID = @SettingsID  ORDER BY cs_LastActivity DESC
ELSE IF @SortBy = 3 AND @SortOrder = 0
    INSERT INTO #PageIndexForUsers (UserID)
    SELECT U.cs_UserID FROM cs_vw_Users_FullUser U, aspnet_UsersInRoles R WHERE R.UserID = U.UserID AND U.cs_UserAccountStatus = @UserAccountStatus AND EnableDisplayInMemberList = 1 AND RoleID = @RoleID and U.SettingsID = @SettingsID  ORDER BY cs_LastActivity

-- Sort by TotalPosts
IF @SortBy = 4 AND @SortOrder = 1
    INSERT INTO #PageIndexForUsers (UserID)
    SELECT U.cs_UserID FROM cs_vw_Users_FullUser U, aspnet_UsersInRoles R WHERE R.UserID = U.UserID AND U.cs_UserAccountStatus = @UserAccountStatus AND EnableDisplayInMemberList = 1 AND RoleID = @RoleID and U.SettingsID = @SettingsID  ORDER BY TotalPosts DESC
ELSE IF @SortBy = 4 AND @SortOrder = 0
    INSERT INTO #PageIndexForUsers (UserID)
    SELECT U.cs_UserID FROM cs_vw_Users_FullUser U, aspnet_UsersInRoles R WHERE R.UserID = U.UserID AND U.cs_UserAccountStatus = @UserAccountStatus AND EnableDisplayInMemberList = 1 AND RoleID = @RoleID and U.SettingsID = @SettingsID  ORDER BY TotalPosts

-- Get the user details
SELECT
	*,
	IsModerator = (SELECT Count(*) FROM cs_Moderators WHERE UserID = U.cs_UserID and SettingsID = @SettingsID)
FROM 
	cs_vw_Users_FullUser U (nolock),
	#PageIndexForUsers
WHERE 
	U.cs_UserID = #PageIndexForUsers.UserID AND
	#PageIndexForUsers.IndexID > @PageLowerBound AND
	#PageIndexForUsers.IndexID < @PageUpperBound  and U.SettingsID = @SettingsID 
ORDER BY
	#PageIndexForUsers.IndexID
END

-- Return the record count if necessary

IF (@ReturnRecordCount = 1)
  SELECT @TotalUsers


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_users_UsersInRole_Get] to public
go
/***********************************************
* Sproc: cs_users_ValidateAnswer
* File Date: 11/29/2006 10:07:32 AM
***********************************************/
Print 'Creating...cs_users_ValidateAnswer'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_users_ValidateAnswereAnswer]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_users_ValidateAnswereAnswer]
GO







--cs_users_ValidateAnswereAnswer 0, 10, 0, 0, null, 0, 1, 0, 0, 3
CREATE          PROCEDURE [dbo].cs_users_ValidateAnswereAnswer
(
	@UserId uniqueidentifier,
	@PasswordAnswer nvarchar(128),
	@IsValid bit output
)
as

if exists (Select UserId from aspnet_membership where Lower(PasswordAnswer) = Lower(@PasswordAnswer))
Begin
	Set @IsValid = 1
End
Else
Begin
	Set @IsValid = 0
End




GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_users_ValidateAnswereAnswer] to public
go
/***********************************************
* Sproc: cs_User_Anonymous_Count
* File Date: 11/29/2006 10:07:30 AM
***********************************************/
Print 'Creating...cs_User_Anonymous_Count'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_User_Anonymous_Count]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_User_Anonymous_Count]
GO


CREATE  procedure [dbo].cs_User_Anonymous_Count
(
	@TimeWindow int,
	@SettingsID int,
	@AnonymousUserCount int out
)
AS
SET Transaction Isolation Level Read UNCOMMITTED
BEGIN
DECLARE @StatDate datetime

	-- Clean up the anonymous users table
	DELETE cs_AnonymousUsers WHERE LastLogin < DateAdd(minute, -@TimeWindow, GetDate())	 and  SettingsID = @SettingsID

	-- Get a count of anonymous users
	SET @AnonymousUserCount = (SELECT count(UserID) FROM cs_AnonymousUsers where SettingsID = @SettingsID)

	-- Do we need to update our forum statistics?
	SET @StatDate = (SELECT MAX(DateCreated) FROM cs_statistics_Site where SettingsID = @SettingsID)
	IF (SELECT TotalAnonymousUsers FROM cs_statistics_Site WHERE DateCreated = @StatDate and SettingsID = @SettingsID) < @AnonymousUserCount 
		UPDATE
			cs_statistics_Site
		SET 
			TotalAnonymousUsers = @AnonymousUserCount
		WHERE
			DateCreated = @StatDate and SettingsID = @SettingsID

END





















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_User_Anonymous_Count] to public
go
/***********************************************
* Sproc: cs_User_Anonymous_Update
* File Date: 11/29/2006 10:07:30 AM
***********************************************/
Print 'Creating...cs_User_Anonymous_Update'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_User_Anonymous_Update]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_User_Anonymous_Update]
GO







CREATE     PROCEDURE [dbo].cs_User_Anonymous_Update
(
	@UserID char(36),
	@LastActivity datetime,
	@LastAction nvarchar(1024) = '',
	@SettingsID int
)
AS
SET Transaction Isolation Level Read UNCOMMITTED
BEGIN
	-- Does the user already exist?
	IF EXISTS (SELECT UserID FROM cs_AnonymousUsers WHERE UserID = @UserID and SettingsID = @SettingsID)

		UPDATE 
			cs_AnonymousUsers
		SET 
			LastLogin = @LastActivity,
			LastAction = @LastAction
		WHERE
			UserID = @UserID and SettingsID = @SettingsID

	ELSE

		INSERT INTO
			cs_AnonymousUsers
			(UserID, LastLogin, LastAction, SettingsID) 
		VALUES
			(@UserID, @LastActivity, @LastAction, @SettingsID)

END
























GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_User_Anonymous_Update] to public
go
/***********************************************
* Sproc: cs_User_Avatar
* File Date: 11/29/2006 10:07:33 AM
***********************************************/
Print 'Creating...cs_User_Avatar'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_User_Avatar]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_User_Avatar]
GO


CREATE procedure [dbo].[cs_User_Avatar]
(
	@UserID	int,
	@SettingsID int
)
AS
SET Transaction Isolation Level Read UNCOMMITTED
BEGIN
		SELECT
			UserID,
			Length,
			ContentType,
			Content,
			DateLastUpdated
		FROM
			cs_UserAvatar
		WHERE
			UserID = @UserID and SettingsID = @SettingsID
END


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_User_Avatar] to public
go
/***********************************************
* Sproc: cs_User_Avatar_CreateUpdateDelete
* File Date: 11/29/2006 10:07:31 AM
***********************************************/
Print 'Creating...cs_User_Avatar_CreateUpdateDelete'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_User_Avatar_CreateUpdateDelete]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_User_Avatar_CreateUpdateDelete]
GO



CREATE procedure [dbo].[cs_User_Avatar_CreateUpdateDelete]
(
    @UserID  int,
    @Content image,
    @ContentType nvarchar(64),
    @ContentSize int,
    @Action  int,
    @SettingsID int,
	@UpdateAllSettingsID bit = 0
)
AS
SET Transaction Isolation Level Read UNCOMMITTED
BEGIN
    -- Remove if already exists from tables: cs_Images, cs_UserAvatar
    DELETE cs_UserAvatar WHERE UserID = @UserID and (SettingsID = @SettingsID or @UpdateAllSettingsID = 1)

    IF @Action = 0 OR @Action = 1 --If the action is 2 (delete) we can skip this part
    BEGIN

        -- Add new entry
        INSERT INTO cs_UserAvatar(UserID, SettingsID, Length, ContentType, [Content], DateLastUpdated) 
			SELECT @UserID, SettingsID, @ContentSize, @ContentType, @Content, GetDate() 
			FROM cs_UserProfile where UserID = @UserID and (SettingsID = @SettingsID or @UpdateAllSettingsID = 1)
    END

END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_User_Avatar_CreateUpdateDelete] to public 
go
/***********************************************
* Sproc: cs_user_CreateUpdateDelete
* File Date: 11/29/2006 10:07:34 AM
***********************************************/
Print 'Creating...cs_user_CreateUpdateDelete'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_user_CreateUpdateDelete]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_user_CreateUpdateDelete]
GO


CREATE  procedure [dbo].cs_user_CreateUpdateDelete 
(
	@cs_UserID int out,
	@UserID uniqueidentifier = null,
	@UserName   nvarchar (64) = '',
	@PropertyNames ntext = null,
	@PropertyValues ntext = null,
	@UserAccountStatus  smallint = 1,
	@IsAnonymous   smallint = 0,
	@IsIgnored     bit = 0,
	@AppUserToken       varchar (128) = '',
	@ForumView   int = 0,
	@TimeZone   float = 0.0,
	@PostRank   binary(1) = 0x0,
	@PostSortOrder   int = 0,
	@IsAvatarApproved   smallint  = 0,
	@ForceLogin   bit   = 0,
	@ModerationLevel  smallint  = 0,
	@EnableThreadTracking  smallint  = 0,
	@EnableDisplayUnreadThreadsOnly smallint  = 0,
	@EnableAvatar    smallint  = 0,
	@EnableDisplayInMemberList  smallint  = 1,
	@EnablePrivateMessages  smallint  = 1,
	@EnableOnlineStatus smallint  = 1,
	@EnableEmail smallint  = 1,
	@EnableHtmlEmail   smallint  = 1,
	@FavoritesShared int = 0,
	@AllowSiteToContact bit = 0,
	@AllowSitePartnersToContact bit = 0,
	@SettingsID int,
	@Action    int,
	@UpdateAllSettingsID bit = 0
)
AS
/*
This sproc returns an int that indicates the CreateUserStatus enum value:
	UnknownFailure = 0
	Created = 1
	DuplicateUsername = 2
	DuplicateEmailAddress = 3
	InvalidFirstCharacter = 4
	DisallowedUsername = 5
	Updated = 6
	Deleted = 7
	InvalidQuestionAnswer = 8
	InvalidPassword = 9
*/

-- first, we need to check if the username is a dup

-- Are we creating a user?
IF @Action = 0
BEGIN
	IF (@IsAnonymous = 1)
	BEGIN
		SELECT @cs_UserID = cs_UserID FROM cs_vw_Users_FullUser WHERE UserName = @UserName AND IsAnonymous = 1 AND SettingsID = @SettingsID
		
		-- Check if the anonymous user already exists
		IF @cs_UserID IS NOT NULL
		Begin
			SELECT 1
			RETURN
		End
		
	END
	ELSE
	BEGIN
		--A WSHA User can exist in multiple sites. We need to find all the site's this user will have access to
		-- and create the coresponding records
		Declare @ApplicationName nvarchar(256)
		Select @ApplicationName = ApplicationName FROM cs_SiteSettings where SettingsID = @SettingsID

		INSERT INTO [cs_Users]([MembershipID], [ForceLogin], [UserAccountStatus], [AppUserToken], [LastActivity], [LastAction])
		VALUES(@UserID, @ForceLogin,@UserAccountStatus, @AppUserToken, getdate(), '')

		Select @cs_UserID = @@Identity

		INSERT INTO cs_UserProfile ( [UserID], [TimeZone], [TotalPosts], 	[PostSortOrder], [PostRank], [IsAvatarApproved], [ModerationLevel], [EnableThreadTracking], [EnableDisplayUnreadThreadsOnly], [EnableAvatar], [EnableDisplayInMemberList], [EnablePrivateMessages], [EnableOnlineStatus], [EnableEmail], [EnableHtmlEmail], [IsIgnored], [MembershipID], [SettingsID], [PropertyNames], [PropertyValues], [FavoritesShared], [AllowSiteToContact], [AllowSitePartnersToContact])
		Select @cs_UserID, @TimeZone, 0, @PostSortOrder, @PostRank, @IsAvatarApproved, @ModerationLevel, @EnableThreadTracking,  @EnableDisplayUnreadThreadsOnly,  @EnableAvatar,   @EnableDisplayInMemberList, @EnablePrivateMessages,   @EnableOnlineStatus,  @EnableEmail, @EnableHtmlEmail, @IsIgnored,  @UserID, SettingsID, @PropertyNames, @PropertyValues, @FavoritesShared, @AllowSiteToContact, @AllowSitePartnersToContact
		FROM cs_SiteSettings where ApplicationName = @ApplicationName
		
		Select 1
		RETURN
	END
END
ELSE
BEGIN

	UPDATE
		cs_UserProfile
	SET
		TimeZone = @TimeZone,
		PostRank = @PostRank,
		PostSortOrder = @PostSortOrder,
		PropertyNames = @PropertyNames,
		PropertyValues = @PropertyValues,
		IsAvatarApproved = @IsAvatarApproved,
		ModerationLevel = @ModerationLevel,
		EnableThreadTracking = @EnableThreadTracking,
		EnableDisplayUnreadThreadsOnly = @EnableDisplayUnreadThreadsOnly,
		EnableAvatar = @EnableAvatar,
		EnableDisplayInMemberList = @EnableDisplayInMemberList,
		EnablePrivateMessages = @EnablePrivateMessages,
		EnableOnlineStatus = @EnableOnlineStatus,
		EnableEmail = @EnableEmail,
		EnableHtmlEmail = @EnableHtmlEmail,
		FavoritesShared = @FavoritesShared,
		AllowSiteToContact = @AllowSiteToContact,
		AllowSitePartnersToContact = @AllowSitePartnersToContact,
		IsIgnored = @IsIgnored
	WHERE
		UserID = @cs_UserID
		AND (SettingsID = @SettingsID or @UpdateAllSettingsID = 1)
	

	-- Update the user's anonymous settings passed in, as well.
	UPDATE aspnet_Users
	SET IsAnonymous = @IsAnonymous
	WHERE UserId = @UserID
  
	-- Some properties will be created/defaulted by SHS Create User.
	-- These values will be updated by Membership.UpdateUser as well. 
	-- Here we just update the properties which fall outside of MembershipUser
	-- First Update the cs_vw_forums_Users table

	UPDATE
		cs_Users
	SET
		AppUserToken = @AppUserToken,
		UserAccountStatus = @UserAccountStatus,
		ForceLogin = @ForceLogin
	WHERE
		 MembershipID = @UserID

	SELECT 6
END


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_user_CreateUpdateDelete] to public
go
/***********************************************
* Sproc: cs_User_Delete
* File Date: 11/29/2006 10:07:34 AM
***********************************************/
Print 'Creating...cs_User_Delete'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_User_Delete]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_User_Delete]
GO


CREATE procedure [dbo].[cs_User_Delete]
(
	@UserID					int,
	@ReassignUserName		nvarchar(256)
)
AS
	SET Transaction Isolation Level Read UNCOMMITTED

	-- locals
	DECLARE	@ApplicationGuid	uniqueidentifier
	DECLARE	@UserGuid			uniqueidentifier
	DECLARE	@ReassignUserID		int


	-- lookup application, user
	SELECT	@ApplicationGuid = ASP.ApplicationId, @UserGuid = ASP.UserId
	FROM	aspnet_Users ASP INNER JOIN cs_Users CS ON ASP.UserId = CS.MembershipID
	WHERE	CS.UserID = @UserID


	-- lookup reassign user
	SELECT	@ReassignUserID = CS.UserID
	FROM	aspnet_Users ASP INNER JOIN cs_Users CS ON ASP.UserId = CS.MembershipID
	WHERE	LoweredUserName = LOWER(@ReassignUserName)
		AND	ApplicationId = @ApplicationGuid


	-- does the reassign user exist?
	IF (@ReassignUserID IS NULL)
	BEGIN
		SELECT 2 -- InvalidReassignUserName
		RETURN
	END


	-- reassign user appears valid
	BEGIN TRANSACTION


	-- be sure posts are set to be reindexed BEFORE they are reassigned
	EXECUTE cs_Posts_ReindexByUser @UserID
	IF (@@ERROR <> 0) GOTO Failure


	-- reassign content
	UPDATE	cs_InkData
	SET		UserID = @ReassignUserID
	WHERE	UserID = @UserID
	IF (@@ERROR <> 0) GOTO Failure

	UPDATE	cs_ModerationAudit
	SET		UserID = @ReassignUserID
	WHERE	UserID = @UserID
	IF (@@ERROR <> 0) GOTO Failure

	UPDATE	cs_PostAttachments
	SET		UserID = @ReassignUserID
	WHERE	UserID = @UserID
	IF (@@ERROR <> 0) GOTO Failure

	UPDATE	cs_PostAttachments_TEMP
	SET		UserID = @ReassignUserID
	WHERE	UserID = @UserID
	IF (@@ERROR <> 0) GOTO Failure

	UPDATE	cs_Posts
	SET		UserID = @ReassignUserID,
			PostAuthor = CONVERT(nvarchar(64), @ReassignUserName)
	WHERE	UserID = @UserID
	IF (@@ERROR <> 0) GOTO Failure

	UPDATE	cs_Posts_Deleted_Archive
	SET		UserID = @ReassignUserID
	WHERE	UserID = @UserID
	IF (@@ERROR <> 0) GOTO Failure

	UPDATE	cs_PostsArchive
	SET		UserName = CONVERT(nvarchar(64), @ReassignUserName)
	FROM	cs_PostsArchive PA INNER JOIN aspnet_Users ASP ON PA.UserName = ASP.UserName INNER JOIN cs_Users CS ON ASP.UserId = CS.MembershipID
	WHERE	CS.UserID = @UserID
	IF (@@ERROR <> 0) GOTO Failure

	UPDATE	cs_PrivateMessages
	SET		UserID = @ReassignUserID
	WHERE	UserID = @UserID
	IF (@@ERROR <> 0) GOTO Failure

	UPDATE	cs_Sections
	SET		MostRecentPostAuthorID = @ReassignUserID,
			MostRecentPostAuthor = CONVERT(nvarchar(64), @ReassignUserName)
	WHERE	MostRecentPostAuthorID = @UserID
	IF (@@ERROR <> 0) GOTO Failure

	UPDATE	cs_Threads
	SET		UserID = @ReassignUserID,
			PostAuthor = CONVERT(nvarchar(64), @ReassignUserName)
	WHERE	UserID = @UserID
	IF (@@ERROR <> 0) GOTO Failure

	UPDATE	cs_Threads
	SET		MostRecentPostAuthorID = @ReassignUserID,
			MostRecentPostAuthor = CONVERT(nvarchar(64), @ReassignUserName)
	WHERE	MostRecentPostAuthorID = @UserID
	IF (@@ERROR <> 0) GOTO Failure

	UPDATE	cs_weblog_Weblogs
	SET		MostRecentArticleAuthor = CONVERT(nvarchar(64), @ReassignUserName)
	WHERE	MostRecentArticleAuthorID = @UserID
	IF (@@ERROR <> 0) GOTO Failure

	UPDATE	cs_weblog_Weblogs
	SET		MostRecentPostAuthor = CONVERT(nvarchar(64), @ReassignUserName)
	WHERE	MostRecentPostAuthorID = @UserID
	IF (@@ERROR <> 0) GOTO Failure


	-- delete content
	DELETE
	FROM	cs_FavoritePosts
	WHERE	OwnerID = @UserID
	IF (@@ERROR <> 0) GOTO Failure

	DELETE
	FROM	cs_FavoriteSections
	WHERE	OwnerID = @UserID
	IF (@@ERROR <> 0) GOTO Failure

	DELETE
	FROM	cs_FavoriteUsers
	WHERE	OwnerID = @UserID OR UserID = @UserID
	IF (@@ERROR <> 0) GOTO Failure

	DELETE
	FROM	cs_FolderFeed
	WHERE	UserID = @UserID
	IF (@@ERROR <> 0) GOTO Failure

	DELETE
	FROM	cs_Folder
	WHERE	UserID = @UserID
	IF (@@ERROR <> 0) GOTO Failure

	DELETE
	FROM	cs_ModerationAudit
	WHERE	ModeratorID = @UserID
	IF (@@ERROR <> 0) GOTO Failure

	DELETE
	FROM	cs_PostRating
	WHERE	UserID = @UserID
	IF (@@ERROR <> 0) GOTO Failure

	DELETE
	FROM	cs_SectionsRead
	WHERE	UserID = @UserID
	IF (@@ERROR <> 0) GOTO Failure

	DELETE
	FROM	cs_Statistics_User
	WHERE	UserID = @UserID
	IF (@@ERROR <> 0) GOTO Failure

	DELETE
	FROM	cs_ThreadRating
	WHERE	UserID = @UserID
	IF (@@ERROR <> 0) GOTO Failure

	DELETE
	FROM	cs_ThreadsRead
	WHERE	UserID = @UserID
	IF (@@ERROR <> 0) GOTO Failure

	DELETE
	FROM	cs_TrackedSections
	WHERE	UserID = @UserID
	IF (@@ERROR <> 0) GOTO Failure

	DELETE
	FROM	cs_TrackedThreads
	WHERE	UserID = @UserID
	IF (@@ERROR <> 0) GOTO Failure

	DELETE
	FROM	cs_UserAvatar
	WHERE	UserID = @UserID
	IF (@@ERROR <> 0) GOTO Failure

	DELETE
	FROM	cs_UserInvitation
	WHERE	UserID = @UserID
	IF (@@ERROR <> 0) GOTO Failure

	DELETE
	FROM	cs_UserReadPost
	WHERE	UserID = @UserID
	IF (@@ERROR <> 0) GOTO Failure

	DELETE
	FROM	cs_Votes
	WHERE	UserID = @UserID
	IF (@@ERROR <> 0) GOTO Failure

	DELETE
	FROM	csm_EmailIds
	WHERE	UserID = @UserID
	IF (@@ERROR <> 0) GOTO Failure

	DELETE
	FROM	files_Downloads
	WHERE	UserID = @UserID
	IF (@@ERROR <> 0) GOTO Failure


	-- delete user
	DELETE
	FROM	cs_Moderators
	WHERE	UserID = @UserID
	IF (@@ERROR <> 0) GOTO Failure

	DELETE
	FROM	cs_UserProfile
	WHERE	UserID = @UserID
	IF (@@ERROR <> 0) GOTO Failure

	DELETE
	FROM	cs_Users
	WHERE	UserID = @UserID
	IF (@@ERROR <> 0) GOTO Failure

	DELETE
	FROM	aspnet_UsersInRoles
	WHERE	UserID = @UserGuid
	IF (@@ERROR <> 0) GOTO Failure

	DELETE
	FROM	aspnet_Profile
	WHERE	UserID = @UserGuid
	IF (@@ERROR <> 0) GOTO Failure

	DELETE
	FROM	aspnet_Membership
	WHERE	UserID = @UserGuid
	IF (@@ERROR <> 0) GOTO Failure

	DELETE
	FROM	aspnet_Users
	WHERE	UserID = @UserGuid
	IF (@@ERROR <> 0) GOTO Failure


	-- no problems occurred
	COMMIT TRANSACTION
	SELECT 1 -- Success
	RETURN


Failure:
	-- something went wrong
	ROLLBACK TRANSACTION
	SELECT 0 -- UnknownFailure
	RETURN


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT EXECUTE ON [dbo].[cs_User_Delete] TO PUBLIC
GO
/***********************************************
* Sproc: cs_user_Get
* File Date: 11/29/2006 10:07:31 AM
***********************************************/
Print 'Creating...cs_user_Get'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_user_Get]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_user_Get]
GO

CREATE      PROCEDURE [dbo].cs_user_Get
(
	@UserID int,
	@Username nvarchar(64) = null,
	@IsOnline bit = 0,
	@LastAction nvarchar(1024) = '',
	@SettingsID int
)
AS
SET Transaction Isolation Level Read UNCOMMITTED
BEGIN
DECLARE @UserIDGUID as uniqueidentifier

	
	-- Are we looking up the user by username or ID?
	IF @Username is not null
	BEGIN
		
		SELECT
			@UserIDGUID = U.UserId
		FROM
			aspnet_Users U,
			cs_SiteSettings S,
			aspnet_Applications A
		WHERE
			S.SettingsID = @SettingsID AND
			A.ApplicationName = S.ApplicationName AND
			A.ApplicationId = U.ApplicationId AND
			U.UserName = @Username

		SELECT
			@UserID = UserID
		FROM
			cs_Users M
		WHERE
			M.MembershipID = @UserIDGUID

		SELECT
			U.*
		FROM
			cs_vw_Users_FullUser U (nolock)
		WHERE 
			UserId = @UserIDGUID AND U.SettingsID = @SettingsID


	END
	ELSE BEGIN
		-- Looking up the user by ID
		
		if(@UserID = 0)
		Begin
			exec cs_GetAnonymousUserID @SettingsID, @UserID output
		End
	
		-- Get the user details
		SELECT
			U.*
		FROM 
			cs_vw_Users_FullUser U (nolock)
		WHERE 
			U.cs_UserID = @UserID and U.SettingsID = @SettingsID
	END

	IF @IsOnline = 1
	BEGIN
		EXEC cs_system_UserIsOnline @UserID, @LastAction, @SettingsID
	END
END






GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_user_Get] to public
go
/***********************************************
* Sproc: cs_User_GetByEmail
* File Date: 11/29/2006 10:07:34 AM
***********************************************/
Print 'Creating...cs_User_GetByEmail'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_User_GetByEmail]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_User_GetByEmail]
GO






create procedure [dbo].cs_User_GetByEmail
(
	@Email		nvarchar(64),
	@SettingsID int
)
AS
SET Transaction Isolation Level Read UNCOMMITTED
SELECT 
	cs_UserID
FROM
	cs_vw_Users_FullUser
WHERE
	Email = @Email and SettingsID = @SettingsID





























GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_User_GetByEmail] to public
go
/***********************************************
* Sproc: cs_User_GetOpmlFeedsFolders
* File Date: 11/29/2006 10:07:33 AM
***********************************************/
Print 'Creating...cs_User_GetOpmlFeedsFolders'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_User_GetOpmlFeedsFolders]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_User_GetOpmlFeedsFolders]
GO


CREATE PROC [dbo].cs_User_GetOpmlFeedsFolders
	@UserId INT
AS

SELECT 	cfo.FolderName,
	cfe.Title,
	cfe.Url,
	cfe.Link
FROM 	cs_Folder cfo
RIGHT OUTER JOIN cs_FolderFeed cff
  ON cff.FolderId = cfo.FolderId
INNER JOIN cs_Feed cfe
  ON cff.FeedId = cfe.FeedId
  AND cff.UserId = @UserId
ORDER BY cfo.FolderName, cfe.Title


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT EXECUTE ON [dbo].cs_User_GetOpmlFeedsFolders  TO PUBLIC
GO

/***********************************************
* Sproc: cs_User_PasswordAnswer_Change
* File Date: 11/29/2006 10:07:32 AM
***********************************************/
Print 'Creating...cs_User_PasswordAnswer_Change'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_User_PasswordAnswer_Change]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_User_PasswordAnswer_Change]
GO



CREATE PROCEDURE [dbo].cs_User_PasswordAnswer_Change
(
	@UserID int,
	@SettingsID int,
	@PasswordQuestion  nvarchar(256),
	@PasswordAnswer  nvarchar(256)
)
AS

Declare @UID uniqueidentifier
Select @UID = MembershipID FROM cs_UserProfile where UserID = @UserID and SettingsID = @SettingsID

BEGIN
	UPDATE
		aspnet_membership
	SET
		PasswordQuestion = @PasswordQuestion,
		PasswordAnswer = @PasswordAnswer
	WHERE
		UserID = @UID
END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_User_PasswordAnswer_Change] to public
go
/***********************************************
* Sproc: cs_User_Rename
* File Date: 11/29/2006 10:07:30 AM
***********************************************/
Print 'Creating...cs_User_Rename'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_User_Rename]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_User_Rename]
GO


CREATE procedure [dbo].[cs_User_Rename]
(
	@UserID					int,
	@DesiredUserName		nvarchar(256),
	@IgnoreDisallowedNames	bit = 0
)
AS
	-- do we care about disallowed names?
	IF (@IgnoreDisallowedNames = 0)
		-- is username allowed?
		IF EXISTS (SELECT * FROM cs_DisallowedNames WHERE @DesiredUserName LIKE REPLACE(DisallowedName, '*', '%'))
		BEGIN
			SELECT 3 -- DisallowedUserName
			RETURN
		END


	-- is the desired username available?
	IF EXISTS (SELECT * FROM aspnet_Users WHERE LoweredUserName = LOWER(@DesiredUserName) AND ApplicationId = (SELECT ApplicationId FROM aspnet_Users ASP INNER JOIN cs_Users CS ON ASP.UserId = CS.MembershipID WHERE CS.UserID = @UserID) AND UserId <> (SELECT CS2.MembershipID FROM cs_Users CS2 WHERE CS2.UserID = @UserID)) -- username is taken
	BEGIN
		SELECT 2 -- DuplicateUserName
		RETURN
	END


	-- username is available, begin update
	BEGIN TRANSACTION


	-- handle ASP.NET membership system
	UPDATE	aspnet_Users
	SET	UserName = @DesiredUserName, LoweredUserName = LOWER(@DesiredUserName)
	FROM	aspnet_Users ASP INNER JOIN cs_Users CS ON ASP.UserId = CS.MembershipID
	WHERE	CS.UserID = @UserID

	IF (@@ERROR <> 0) GOTO Failure


	-- handle posts
	UPDATE	cs_Posts
	SET	PostAuthor = @DesiredUserName
	WHERE	UserID = @UserID

	IF (@@ERROR <> 0) GOTO Failure


	-- handle post archive
	UPDATE	cs_PostsArchive
	SET	UserName = @DesiredUserName
	FROM	cs_PostsArchive PA INNER JOIN aspnet_Users ASP ON PA.UserName = ASP.UserName INNER JOIN cs_Users CS ON ASP.UserId = CS.MembershipID
	WHERE	CS.UserID = @UserID

	IF (@@ERROR <> 0) GOTO Failure


	-- handle sections
	UPDATE	cs_Sections
	SET	MostRecentPostAuthor = @DesiredUserName
	WHERE	MostRecentPostAuthorID = @UserID

	IF (@@ERROR <> 0) GOTO Failure


	-- handle threads
	UPDATE	cs_Threads
	SET	MostRecentPostAuthor = @DesiredUserName
	WHERE	MostRecentPostAuthorID = @UserID

	IF (@@ERROR <> 0) GOTO Failure


	UPDATE	cs_Threads
	SET	PostAuthor = @DesiredUserName
	WHERE	UserID = @UserID

	IF (@@ERROR <> 0) GOTO Failure


	-- handle blogs
	UPDATE	cs_weblog_Weblogs
	SET	MostRecentArticleAuthor = @DesiredUserName
	WHERE	MostRecentArticleAuthorID = @UserID

	IF (@@ERROR <> 0) GOTO Failure


	UPDATE	cs_weblog_Weblogs
	SET	MostRecentPostAuthor = @DesiredUserName
	WHERE	MostRecentPostAuthorID = @UserID

	IF (@@ERROR <> 0) GOTO Failure


	-- be sure posts are reindexed
	EXECUTE cs_Posts_ReindexByUser @UserID

	IF (@@ERROR <> 0) GOTO Failure


	-- no problems occurred
	COMMIT TRANSACTION
	SELECT 1 -- Success
	RETURN


Failure:
	-- something went wrong
	ROLLBACK TRANSACTION
	SELECT 0 -- UnknownFailure
	RETURN


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT EXECUTE ON [dbo].[cs_User_Rename] TO PUBLIC
GO
/***********************************************
* Sproc: cs_User_ToggleSettings
* File Date: 11/29/2006 10:07:32 AM
***********************************************/
Print 'Creating...cs_User_ToggleSettings'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_User_ToggleSettings]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_User_ToggleSettings]
GO


CREATE   procedure [dbo].[cs_User_ToggleSettings]
(
	@UserID int,
	@ModerationLevel int,
	@UserAccountStatus int,
	@ForceLogin bit = 0,
	@IsAvatarApproved bit,
	@ModeratorID int,
	@SettingsID int,
	@UpdateAllSettingsID bit = 0
)
AS
SET Transaction Isolation Level Read UNCOMMITTED
BEGIN

	DECLARE	@CurrentUserAccountStatus	int
	SELECT	@CurrentUserAccountStatus = UserAccountStatus
	FROM	cs_Users
	WHERE	UserID = @UserID

	UPDATE 
		cs_Users
	SET
		UserAccountStatus = @UserAccountStatus,
		ForceLogin = @ForceLogin
	WHERE
		UserID = @UserID 

	DECLARE	@CurrentModerationLevel	int
	SELECT	@CurrentModerationLevel = ModerationLevel
	FROM	cs_UserProfile
	WHERE	UserID = @UserID
	AND		SettingsID = @SettingsID

	UPDATE
		cs_UserProfile
	SET
		ModerationLevel = @ModerationLevel,
		IsAvatarApproved = @IsAvatarApproved
	WHERE
		UserID = @UserID AND (SettingsID = @SettingsID or @UpdateAllSettingsID = 1)

	IF (@ModerationLevel != @CurrentModerationLevel)		-- moderation level has changed
	BEGIN
		IF (@ModerationLevel = 0)
			exec cs_system_ModerationAction_AuditEntry 11, @ModeratorID, null, @UserID, null, @SettingsID
		ELSE
			exec cs_system_ModerationAction_AuditEntry 10, @ModeratorID, null, @UserID, null, @SettingsID
	END

	IF (@UserAccountStatus != @CurrentUserAccountStatus)	-- user account status has changed
	BEGIN
		IF @UserAccountStatus = 1
			exec cs_system_ModerationAction_AuditEntry 13, @ModeratorID, null, @UserID, null, @SettingsID
		ELSE
			exec cs_system_ModerationAction_AuditEntry 12, @ModeratorID, null, @UserID, null, @SettingsID
	END

END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_User_ToggleSettings] to public
go


/***********************************************
* Sproc: cs_Vote_Create
* File Date: 11/29/2006 10:07:31 AM
***********************************************/
Print 'Creating...cs_Vote_Create'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Vote_Create]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Vote_Create]
GO


create procedure [dbo].cs_Vote_Create (
  @PostID int,
  @UserID int,
  @Vote nvarchar(2),
  @SettingsID int
)
AS
IF NOT EXISTS (
    SELECT
        PostID 
    FROM 
        cs_VoteSummary
    WHERE 
        PostID = @PostID AND Vote = @Vote and SettingsID = @SettingsID
)
BEGIN
        INSERT INTO 
            cs_VoteSummary
        VALUES
        (
            @PostID,
            @Vote,
            1,
	    @SettingsID
        )

	INSERT INTO
		cs_Votes
	VALUES
	(
		@PostID,
		@UserID, 
		@Vote,
		@SettingsID
	)	
END
ELSE
BEGIN
	IF EXISTS(SELECT UserID FROM cs_Votes WHERE PostID = @PostID AND UserID = @UserID)
		-- Already voted
		RETURN

        UPDATE 
          cs_VoteSummary
        SET 
          VoteCount  =  VoteCount + 1
        WHERE 
          PostID = @PostID AND
          Vote = @Vote and SettingsID = @SettingsID

	INSERT INTO
		cs_Votes
	VALUES
	(
		@PostID,
		@UserID, 
		@Vote,
		@SettingsID
	)	
	
END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_Vote_Create] to public
go
/***********************************************
* Sproc: cs_Vote_GetSummary
* File Date: 11/29/2006 10:07:30 AM
***********************************************/
Print 'Creating...cs_Vote_GetSummary'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO


if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Vote_GetSummary]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Vote_GetSummary]
GO

CREATE   procedure [dbo].cs_Vote_GetSummary (
	@PostID int,
	@SettingsID int
)
AS
SET Transaction Isolation Level Read UNCOMMITTED
BEGIN
  SELECT
	Vote,
	VoteCount
  FROM
	cs_VoteSummary
  WHERE
	PostID = @PostID

  SELECT
	UserID,
	Vote
  FROM
	cs_Votes
  WHERE
	PostID = @PostID
END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_Vote_GetSummary] to public
go
/***********************************************
* Sproc: cs_weblog_DeleteStaleSpamComments
* File Date: 11/29/2006 10:07:31 AM
***********************************************/
Print 'Creating...cs_weblog_DeleteStaleSpamComments'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_weblog_DeleteStaleSpamComments]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_weblog_DeleteStaleSpamComments]
GO



CREATE   PROCEDURE [dbo].cs_weblog_DeleteStaleSpamComments
(
	@SettingsID int,
	@ExpirationDays int = 30
)
AS

SET Transaction Isolation Level Read UNCOMMITTED


DECLARE	@CommentsToDelete TABLE
		(PostID int)

-- temporarily store posts to delete
INSERT	@CommentsToDelete
		(PostID)
SELECT	P.PostID
FROM	cs_Posts P INNER JOIN cs_Sections S ON P.SectionID = S.SectionID
WHERE	S.ApplicationType = 1									-- only posts in blogs
	AND	P.ApplicationPostType IN (4, 8)							-- only comments/trackbacks
	AND	(P.PostStatus & 2) = 2									-- only posts marked as spam
	AND	P.PostDate < dateadd(d, -@ExpirationDays, getdate())	-- only posts that have been around for a while

-- archive deleted posts
INSERT	cs_posts_deleted_archive
		(PostID, UserID, SectionID, SettingsID, ApplicationType, Body, Subject, IPAddress, DeletedDate, ParentID, ThreadID, PostLevel, PostType, PropertyNames, PropertyValues, SpamScore, PostStatus)
SELECT	P.PostID, P.UserID, P.SectionID, P.SettingsID, 1, P.Body, P.Subject, P.IPAddress, getdate(), P.ParentID, P.ThreadID, P.PostLevel, P.PostType, P.PropertyNames, P.PropertyValues, P.SpamScore, P.PostStatus
FROM	cs_Posts P INNER JOIN @CommentsToDelete D ON P.PostID = D.PostID

-- actually delete posts
DELETE	P
FROM	cs_Posts P INNER JOIN @CommentsToDelete D ON P.PostID = D.PostID


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO


grant execute on [dbo].[cs_weblog_DeleteStaleSpamComments] to public
go

/***********************************************
* Sproc: cs_weblog_Feedback_Get
* File Date: 11/29/2006 10:07:31 AM
***********************************************/
Print 'Creating...cs_weblog_Feedback_Get'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_weblog_Feedback_Get]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_weblog_Feedback_Get]
GO
/***********************************************
* Sproc: cs_weblog_PostsByMonth
* File Date: 11/29/2006 10:07:30 AM
***********************************************/
Print 'Creating...cs_weblog_PostsByMonth'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_weblog_PostsByMonth]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_weblog_PostsByMonth]
GO


CREATE proc [dbo].cs_weblog_PostsByMonth
(
	@SectionID int,
	@Year int,
	@Month int
)
as

SET Transaction Isolation Level Read UNCOMMITTED


Select @Month as [Month], @Year as [Year], Day(p.UserTime) as [Day], Count(*) as [Count] 
From cs_Posts p
where p.SectionID = @SectionID and p.IsApproved = 1 and P.ApplicationPostType = 1 and p.PostLevel = 1 and Month(p.UserTime) = @Month and Year(p.UserTime) = @Year and p.PostDate <= getdate()
Group by Day(p.UserTime) order by  [Day]




GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_weblog_PostsByMonth] to public
go
/***********************************************
* Sproc: cs_weblog_PostsByMonthList
* File Date: 11/29/2006 10:07:30 AM
***********************************************/
Print 'Creating...cs_weblog_PostsByMonthList'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_weblog_PostsByMonthList]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_weblog_PostsByMonthList]
GO


CREATE proc [dbo].cs_weblog_PostsByMonthList
(
	@SectionID int
)
as

SET Transaction Isolation Level Read UNCOMMITTED

Select Month(p.UserTime) as [Month], Year(p.UserTime) as [Year], 1 as Day, Count(*) as [Count] 
From cs_Posts p
where p.SectionID = @SectionID and p.IsApproved = 1 and p.ApplicationPostType = 1 and p.PostDate <= getdate()
Group by Year(p.UserTime), Month(p.UserTime) order by [Year] desc, [Month] desc




GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_weblog_PostsByMonthList] to public
go
/***********************************************
* Sproc: cs_weblog_PostSet
* File Date: 11/29/2006 10:07:33 AM
***********************************************/
Print 'Creating...cs_weblog_PostSet'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_weblog_PostSet]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_weblog_PostSet]
GO





CREATE PROCEDURE dbo.cs_weblog_PostSet
(
	@SectionID int,
	@PostID	int,
	@PostName nvarchar(512) = null,
	@PageIndex int,
	@PageSize int,
	@UserID int,
	@ReturnFullThread bit,
	@IncludeCategories bit,
	@TotalRecords int output
)
AS

BEGIN

SET Transaction Isolation Level Read UNCOMMITTED

DECLARE @PageLowerBound int
DECLARE @PageUpperBound int
DECLARE @ThreadID int


-- Get the ThreadID
if(@PostName is null)
Begin
	SELECT
		@ThreadID = ThreadID
	FROM 
		cs_Posts
	WHERE 
		PostID = @PostID and SectionID = @SectionID
End
Else
Begin
	SELECT
		@ThreadID = P.ThreadID, @PostID = P.PostID
	FROM 
		cs_Posts P
	WHERE 
		P.SectionID = @SectionID and P.PostName = @PostName

End

--Now we need the main post
	SELECT
		P.PostID, P.ThreadID, P.ParentID, P.PostAuthor, P.UserID, P.SectionID, P.PostLevel, 
		P.SortOrder, P.Subject, P.PostDate, P.IsApproved, P.IsLocked, P.IsIndexed, P.TotalViews, 
		P.Body, P.FormattedBody, P.IPAddress, P.PostType, P.PostMedia, P.EmoticonID, P.SettingsID, 
		P.AggViews, P.PostPropertyNames, P.PostPropertyValues, P.PostConfiguration,
		T.PostAuthor as ThreadPostAuthor,  T.UserID as ThreadUserID,
		T.PostDate as ThreadPostDate, T.ThreadDate, 
		T.LastViewedDate, T.StickyDate, 
		T.TotalViews, --??
		T.TotalReplies, T.TotalReplies as Replies, 
		T.MostRecentPostAuthorID, T.MostRecentPostAuthor, T.MostRecentPostID, 
		T.IsLocked as ThreadIsLocked, 
		T.IsSticky, T.IsApproved as ThreadIsApproved, 
		T.RatingSum, T.TotalRatings, T.ThreadEmoticonID, T.ThreadStatus, 
		P.PostName, P.UserTime,P.ApplicationPostType, P.Points as PostPoints,
		P.PostAuthor as Username,
		EditNotes = null,
		AttachmentFilename,ContentType, IsRemote, FriendlyFileName, ContentSize,[FileName], p.Created, p.Height, p.Width,
		IsModerator = 0,
		HasRead = 0 -- not used,
		, P.PostStatus, P.SpamScore
	FROM 
		cs_vw_PostsWithAttachmentDetails P (nolock),
		cs_Threads T
	WHERE 
		P.PostID = @PostID AND
		T.ThreadID = P.ThreadID



--Do we want/need categories
	IF @IncludeCategories = 1
	Begin
		Select [Name]
		FROM   cs_Post_Categories PC, cs_Posts_InCategories PIC
		Where  PC.CategoryID = PIC.CategoryID AND PIC.PostID = @PostID
	End


--Are we going to honor paging?
if @ReturnFullThread = 0
Begin
	-- First set the rowcount
	DECLARE @RowsToReturn int
	SET @RowsToReturn = @PageSize * (@PageIndex + 1)
	

	-- Set the page bounds
	SET @PageLowerBound = @PageSize * @PageIndex
	SET @PageUpperBound = @PageLowerBound + @PageSize + 1


	-- Create a temp table to store the select results
	CREATE TABLE #PageIndex 
	(
		IndexID int IDENTITY (1, 1) NOT NULL,
		PostID int
	)

	INSERT INTO #PageIndex (PostID)
	SELECT P.PostID 
	FROM cs_Posts P (nolock)
	WHERE P.IsApproved = 1 AND P.ThreadID = @ThreadID AND P.PostLevel > 1 and P.ApplicationPostType <> 16 -- Do not display Personal Comments (private)
	ORDER BY PostDate

	Set @TotalRecords = @@rowcount

	SET ROWCOUNT @RowsToReturn

	-- Select the individual posts
	SELECT
		P.PostID, P.ThreadID, P.ParentID, P.PostAuthor, P.UserID, P.SectionID, P.PostLevel, P.SortOrder, P.Subject, P.PostDate, P.IsApproved,
		P.IsLocked, P.IsIndexed, P.TotalViews, P.Body, P.FormattedBody, P.IPAddress, P.PostType, P.PostMedia, P.EmoticonID, P.SettingsID, P.AggViews,
		P.PropertyNames as PostPropertyNames, P.PropertyValues as PostPropertyValues,
		P.PostConfiguration, P.PostName, P.ApplicationPostType, P.UserTime,
		P.Points as PostPoints,
		T.PostAuthor as ThreadPostAuthor,  T.UserID as ThreadUserID,
		T.PostDate as ThreadPostDate, T.ThreadDate, 
		T.LastViewedDate, T.StickyDate, 
		T.TotalViews, --??
		T.TotalReplies, 
		T.MostRecentPostAuthorID, T.MostRecentPostAuthor, T.MostRecentPostID, 
		T.IsLocked as ThreadIsLocked, 
		T.IsSticky, T.IsApproved as ThreadIsApproved, 
		T.RatingSum, T.TotalRatings, T.ThreadEmoticonID, T.ThreadStatus, 
		#PageIndex.*,
		P.PostAuthor as Username,
		EditNotes = null, 
		AttachmentFilename = null,
		Replies = 0,
		IsModerator = 0, 
		HasRead = 0 -- not used
		, P.PostStatus, P.SpamScore
	FROM 
		cs_Posts P (nolock),
		cs_Threads T,
		#PageIndex
	WHERE 
		P.PostID = #PageIndex.PostID AND
		T.ThreadID = P.ThreadID AND
		#PageIndex.IndexID > @PageLowerBound AND
		#PageIndex.IndexID < @PageUpperBound
	ORDER BY
		IndexID

	--SELECT @TotalRecords = count(*) FROM #PageIndex  

	DROP TABLE #PageIndex
END
ELSE --No Paging, just get all of the comments/trackbacks
BEGIN
	-- Select the individual posts
	SELECT
		P.PostID, P.ThreadID, P.ParentID, P.PostAuthor, P.UserID, P.SectionID, P.PostLevel, P.SortOrder, P.Subject, P.PostDate, P.IsApproved,
		P.IsLocked, P.IsIndexed, P.TotalViews, P.Body, P.FormattedBody, P.IPAddress, P.PostType, P.PostMedia, P.EmoticonID, P.SettingsID, P.AggViews,
		P.PropertyNames as PostPropertyNames, P.PropertyValues as PostPropertyValues,
		P.PostConfiguration, P.PostName, P.ApplicationPostType, P.UserTime,
		P.Points as PostPoints, P.PostStatus, P.SpamScore,
		T.PostAuthor as ThreadPostAuthor,  T.UserID as ThreadUserID,
		T.PostDate as ThreadPostDate, T.ThreadDate, 
		T.LastViewedDate, T.StickyDate, 
		T.TotalViews, --??
		T.TotalReplies, 
		T.MostRecentPostAuthorID, T.MostRecentPostAuthor, T.MostRecentPostID, 
		T.IsLocked as ThreadIsLocked, 
		T.IsSticky, T.IsApproved as ThreadIsApproved, 
		T.RatingSum, T.TotalRatings, T.ThreadEmoticonID, T.ThreadStatus, 
		P.PostAuthor as Username,
		EditNotes = null, 
		AttachmentFilename = null,
		Replies = 0, 
		IsModerator = 0, 
		HasRead = 0 -- not used
	FROM 
		cs_Posts P,
		cs_Threads t
	WHERE 
		P.ThreadID = t.ThreadID AND
		
		t.ThreadID = @ThreadID AND P.PostLevel > 1 AND P.IsApproved = 1 
		AND P.PostType <> 16 -- Do not display Personal Comments (private)
	ORDER BY
		P.PostID

	SELECT @TotalRecords = Count(P.PostID) FROM cs_Posts P (nolock) WHERE P.IsApproved = 1 AND P.ThreadID = @ThreadID AND P.PostLevel <> 1 and P.PostType <> 16

END

END



GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT  EXECUTE  ON [dbo].[cs_weblog_PostSet]  TO [public]
GO


/***********************************************
* Sproc: cs_weblog_Posts_GetPostSet
* File Date: 11/29/2006 10:07:30 AM
***********************************************/
Print 'Creating...cs_weblog_Posts_GetPostSet'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_weblog_Posts_GetPostSet]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_weblog_Posts_GetPostSet]
GO

--Replaced by cs_shared_Threads_GetThreadSet
/***********************************************
* Sproc: cs_weblog_Post_Create
* File Date: 11/29/2006 10:07:31 AM
***********************************************/
Print 'Creating...cs_weblog_Post_Create'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_weblog_Post_Create]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_weblog_Post_Create]
GO



CREATE   PROCEDURE [dbo].cs_weblog_Post_Create
(
	@SectionID int,
	@ParentID int,
	@AllowDuplicatePosts bit,
	@DuplicateIntervalInMinutes int = 0,
	@Subject nvarchar(256),
	@UserID int,
	@PostAuthor nvarchar(64) = null,
	@Body ntext,
	@FormattedBody ntext,
	@EmoticonID int = 0,
	@IsLocked bit,
	@IsSticky bit,
	@IsApproved bit = 0,
	@IsTracked bit = 0,
	@StickyDate datetime,
	@PostType int = 0,
	@PostMedia int = 0,
	@PostDate datetime,
	@UserTime datetime,
	@UserHostAddress nvarchar(32),
	@PostName nvarchar(256) = null,
	@TitleUrl nvarchar(256) = null,
	@PostConfig int = 0,
	@BlogPostType tinyint = 1,
	@Categories nvarchar(4000) = null,
	@PropertyNames ntext = null,
	@PropertyValues ntext = null,
	@SettingsID int,
	@SpamScore int = 0,
	@PostStatus int = 0,
	@PostID int out
) 
AS
SET NOCOUNT ON
DECLARE @MaxSortOrder int
DECLARE @ParentLevel int
DECLARE @ThreadID int
DECLARE @ParentSortOrder int
DECLARE @NextSortOrder int
DECLARE @EnablePostStatistics bit
DECLARE @TrackThread bit
DECLARE @IsComment bit

if(@PostName is not null)
Begin

	if exists(Select p.PostID FROM cs_Posts p where p.SectionID = @SectionID and p.PostName = @PostName and p.ApplicationPostType = @BlogPostType)
	Begin
		Return 2
	End
End

if(@BlogPostType = 1 OR @BlogPostType = 2)
	SET @IsComment = 0
Else
	SET @IsComment = 1

-- set the PostDate
IF @PostDate IS NULL
	SET @PostDate = GetDate()

-- set the username
IF @PostAuthor IS NULL
	SELECT 
		@PostAuthor = UserName
	FROM 
		cs_vw_Users_FullUser 
	WHERE 
		cs_UserID = @UserID

-- Do we care about duplicates?
IF @AllowDuplicatePosts = 0 and @IsComment = 1
BEGIN
	DECLARE @IsDuplicate bit
	exec cs_system_DuplicatePost @UserID, @Body, @DuplicateIntervalInMinutes, @SettingsID, @IsDuplicate output

	IF @IsDuplicate = 1
	BEGIN
		SET @PostID = -1	
		RETURN 1-- Exit with error code.
	END
END

-- we need to get the SectionID, if the ParentID is not null (there should be a SectionID)
IF @SectionID = 0 AND @ParentID <> 0
	SELECT 
		@SectionID = SectionID
	FROM 
		cs_Posts (nolock) 
	WHERE 
		PostID = @ParentID

--Set @ModeratedForum = (@PostConfig & 16)
SELECT 
	@EnablePostStatistics = EnablePostStatistics
FROM 
	cs_Sections (nolock)
WHERE 
	SectionID = @SectionID and SettingsID = @SettingsID

-- Determine if this post will be approved.
-- If the forum is NOT moderated, then the post will be approved by default.
SET NOCOUNT ON
BEGIN TRAN


IF @ParentID = 0	-- parameter indicating this is a top-level post (for a new thread)
BEGIN
	-- First we create a new ThreadID.

	-- check the StickyDate to ensure it's not null
	IF @StickyDate < @PostDate
		SET @StickyDate = @PostDate

	INSERT cs_Threads 	
		( SectionID,
		PostDate, 
		UserID, 
		PostAuthor, 
		ThreadDate, 
		MostRecentPostAuthor, 
		MostRecentPostAuthorID, 	
		MostRecentPostID, 
		IsLocked, 
		IsApproved,
		IsSticky, 
		StickyDate, 
		ThreadEmoticonID,
		SettingsID )
	VALUES
		( @SectionID, 
		@PostDate, 
		@UserID, 
		@PostAuthor,
		@PostDate,
		@PostAuthor,
		@UserID, 
		0,	-- MostRecentPostID, which we don't know until after post INSERT below.
		@IsLocked,
		@IsApproved,
		@IsSticky,
		@StickyDate,
		@EmoticonID,
		@SettingsID )

	-- Get the new ThreadID
	SELECT @ThreadID = @@IDENTITY
		
	-- Now we add the new post
	INSERT cs_Posts 
		( SectionID, 
		ThreadID, 
		ParentID, 
		PostLevel, 
		SortOrder, 
		Subject, 
		UserID, 
		PostAuthor, 
		IsApproved, 
		IsLocked, 
		Body, 
		FormattedBody, 
		PostType, 
		PostMedia, 
		PostDate, 
		IPAddress, 
		EmoticonID,
		PropertyNames,
		PropertyValues,
		SettingsID,
		PostName,
		PostConfiguration,
		UserTime,
		ApplicationPostType,
		PostStatus,
		SpamScore
		
	        )
	VALUES 
		( @SectionID, 
		@ThreadID, 
		0, 	-- ParentID, which we don't know until after INSERT
		1, 	-- PostLevel, 1 marks start/top/first post in thread.
		1, 	-- SortOrder (not in use at this time)
		@Subject, 
		@UserID, 
		@PostAuthor,
		@IsApproved, 
		@IsLocked, 
		@Body, 
		@FormattedBody, 
		@PostType, 
		@PostMedia, 
		@PostDate, 
		@UserHostAddress, 
		@EmoticonID,
		@PropertyNames,
		@PropertyValues,
		@SettingsID,
		@PostName,
		@PostConfig,
		@UserTime,
		@BlogPostType,
		@PostStatus,
		@SpamScore )
		

	-- Get the new PostID
	SELECT 
		@PostID = @@IDENTITY


	-- Update the new Thread with the new PostID
	UPDATE 
		cs_Threads
	SET 
		MostRecentPostID = @PostID
	WHERE 
		ThreadID = @ThreadID

	-- Update the new Post's ParentID with the new PostID
	UPDATE 
		cs_Posts
	SET 
		ParentID = @PostID
	WHERE 
		PostID = @PostID

END
ELSE BEGIN	-- @ParentID <> 0 means there is a reply to an existing post

	-- Get the Post Information for what we are replying to
	SELECT 
		@ThreadID = ThreadID,
		@SectionID = SectionID,
		@ParentLevel = PostLevel,
		@ParentSortOrder = SortOrder
	FROM 
		cs_Posts
	WHERE 
		PostID = @ParentID

	-- Is there another post at the same level or higher?
	SET @NextSortOrder = (
		SELECT 	
			MIN(SortOrder) 
		FROM 
			cs_Posts 
		WHERE 
			PostLevel <= @ParentLevel 
			AND SortOrder > @ParentSortOrder 
			AND ThreadID = @ThreadID )

	IF @NextSortOrder > 0
	BEGIN
		-- Move the existing posts down
		UPDATE 
			cs_Posts
		SET 
			SortOrder = SortOrder + 1
		WHERE 
			ThreadID = @ThreadID
			AND SortOrder >= @NextSortOrder

		SET @MaxSortOrder = @NextSortOrder

	END
   	ELSE BEGIN 	-- There are no posts at this level or above
	
		-- Find the highest sort order for this parent
		SELECT 
			@MaxSortOrder = MAX(SortOrder) + 1
		FROM 
			cs_Posts
		WHERE 
			ThreadID = @ThreadID

	END 

	-- Insert the new post
	INSERT cs_Posts 
		( SectionID, 
		ThreadID, 
		ParentID, 
		PostLevel, 
		SortOrder, 
		Subject, 
		UserID, 
		PostAuthor, 
		IsApproved, 
		IsLocked, 
		Body, 
		FormattedBody, 
		PostType, 
		PostMedia, 
		PostDate, 
		IPAddress, 
		EmoticonID,
		PropertyNames,
		PropertyValues,
		SettingsID,
		PostName,
		PostConfiguration,
		UserTime,
		ApplicationPostType,
		PostStatus,
		SpamScore )
	VALUES 
		( @SectionID, 
		@ThreadID, 
		@ParentID, 
		@ParentLevel + 1, 
		@MaxSortOrder,
		@Subject, 
		@UserID, 
		@PostAuthor, 
		@IsApproved, 
		@IsLocked, 
		@Body, 
		@FormattedBody, 
		@PostType, 
		@PostMedia, 
		@PostDate, 
		@UserHostAddress, 
		@EmoticonID,
		@PropertyNames,
		@PropertyValues,
		@SettingsID,
		@PostName,
		@PostConfig,
		@UserTime,
		@BlogPostType,
		@PostStatus,
		@SpamScore  )


		-- Grab the new PostID and update the ThreadID's info
		SELECT 
			@PostID = @@IDENTITY 


	-- Now check to see if this post is Approved by default.
	-- If so, we go ahead and update the Threads table for the MostRecent items.
	IF @IsApproved = 1 
	BEGIN		
		-- To cut down on overhead, I've elected to update the thread's info
		-- directly from here, without running cs_system_UpdateThread since
		-- I already have all of the information that this sproc would normally have to lookup.
		IF @StickyDate < @PostDate
			SET @StickyDate = @PostDate

		UPDATE
			cs_Threads 	
		SET 
			--MostRecentPostAuthor = @PostAuthor, << We do not track comments
			--MostRecentPostAuthorID = @UserID, << We do not track comments
			--MostRecentPostID = @PostID, << We do not track Comments
			TotalReplies = (SELECT COUNT(*) FROM cs_Posts p WHERE  p.ApplicationPostType & 12 <> 0 and   p.ThreadID = @ThreadID AND p.IsApproved = 1 AND p.PostLevel > 1)
			--IsLocked = @IsLocked,
			--StickyDate = @StickyDate,	-- this makes the thread a sticky/announcement, even if it's a reply.
			--ThreadDate = @PostDate
		WHERE
			ThreadID = @ThreadID
	END
--	ELSE
/*
	BEGIN
		-- Moderated Posts: get the new PostID
		SELECT @PostID = @@IDENTITY 
	END
*/
/*
	-- Clean up ThreadsRead (this should work very well now)
	-- Not tracking in blogs
	DELETE
		cs_ThreadsRead
	WHERE
		ThreadID = @ThreadID 
		AND UserID <> @UserID
*/
END

--Increments posts totals ignoring settings id
IF @EnablePostStatistics = 1 AND @UserID > 0 AND @IsApproved = 1
BEGIN
	EXEC cs_system_UpdateUserPostCount @SectionID, @UserID, @SettingsID
END

IF(@BlogPostType = 1 OR @BlogPostType = 2)
BEGIN
	IF @IsTracked = 1
		BEGIN
		INSERT INTO cs_TrackedThreads ( ThreadID, UserID, SettingsID )
		VALUES	( @ThreadID, @UserID, @SettingsID )
	END
	
	exec cs_Posts_UpdatePostsInCategories @Categories, @SectionID, @PostID, @SettingsID, 1
END

--exec cs_weblog_UpdateContentHistory @SectionID, @BlogPostType

	
COMMIT TRAN

SET NOCOUNT OFF

SELECT @PostID = @PostID
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





grant execute on [dbo].[cs_weblog_Post_Create] to public
go

/***********************************************
* Sproc: cs_weblog_Post_Delete
* File Date: 11/29/2006 10:07:30 AM
***********************************************/
Print 'Creating...cs_weblog_Post_Delete'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_weblog_Post_Delete]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_weblog_Post_Delete]
GO



CREATE   PROCEDURE [dbo].cs_weblog_Post_Delete
(
	@SectionID int,
	@PostID int,
	@UserID int,
	@BlogPostType tinyint = 1,
	@SettingsID int
) 
AS

SET Transaction Isolation Level Read UNCOMMITTED

Declare @ThreadID int
Select @ThreadID = ThreadID FROM cs_Posts where PostID = @PostID

if(@BlogPostType = 4 or @BlogPostType = 8)
Begin
	Delete FROM cs_Posts where PostID = @PostID
End
ELSE
Begin

	Delete FROM cs_Posts_InCategories where PostID = @PostID and SettingsID =  @SettingsID
	Delete FROM cs_PostAttachments where PostID = @PostID and SectionID = @SectionID and SettingsID = @SettingsID
	Delete FROM cs_ThreadRating where ThreadID = @ThreadID and SettingsID = @SettingsID
	Delete FROM cs_Referrals where PostID = @PostID and SectionID = @SectionID and SettingsID = @SettingsID
	Delete FROM cs_TrackedThreads where ThreadID = @ThreadID and SettingsID = @SettingsID
	Delete FROM cs_Posts where ThreadID = @ThreadID and SectionID = @SectionID and SettingsID = @SettingsID
	Delete FROM cs_Threads where ThreadID = @ThreadID and SectionID = SectionID

End


-- exec cs_weblog_UpdateContentHistory @SectionID = @SectionID, @BlogPostTypeFilter = @BlogPostType
exec cs_Posts_UpdatePostsInCategories @SectionID = @SectionID, @PostID = @PostID

-- Update thread statistics
exec cs_system_ResetThreadStatistics @ThreadID



GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





grant execute on [dbo].[cs_weblog_Post_Delete] to public
go

/***********************************************
* Sproc: cs_weblog_Post_Get
* File Date: 11/29/2006 10:07:32 AM
***********************************************/
Print 'Creating...cs_weblog_Post_Get'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_weblog_Post_Get]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_weblog_Post_Get]
GO




CREATE PROCEDURE dbo.cs_weblog_Post_Get --11, 36, 0, 1, 0
(

	@PostID	int,
	@IncludeCategories bit,
	@IsApprovedFilter bit,
	@SettingsID int
)
AS
BEGIN

DECLARE	@SectionID int
DECLARE @ThreadID int 
DECLARE @SortOrder int
DECLARE @IsApproved bit


SELECT 
	@SectionID = SectionID,
	@ThreadID = ThreadID, 
	@SortOrder=SortOrder,
	@IsApproved = IsApproved
FROM 
	cs_Posts (nolock) 
WHERE 
	PostID = @PostID and  SettingsID = @SettingsID


SELECT
	P.PostID, P.ThreadID, P.ParentID, P.PostAuthor, P.UserID, P.SectionID, P.PostLevel, P.SortOrder, P.Subject, P.PostDate, P.IsApproved,
	P.IsLocked, P.IsIndexed, P.TotalViews, P.Body, P.FormattedBody, P.IPAddress, P.PostType, P.PostMedia, P.EmoticonID, P.SettingsID, P.AggViews,
	P.PostPropertyNames, P.PostPropertyValues,
	P.PostConfiguration, P.UserTime, P.PostName,P.ApplicationPostType,
	P.Points as PostPoints,
	T.*, U.*,
	T.ThreadDate,
	T.StickyDate,
	T.IsLocked,
	T.IsSticky,
	HasRead = 0,
	EditNotes = null, -- (SELECT EditNotes FROM cs_PostEditNotes WHERE PostID = P.PostID),
	IndexInThread = 0,  -- (SELECT Count(PostID) FROM cs_Posts P1 WHERE IsApproved = 1 AND ThreadID = @ThreadID AND SortOrder <= (SELECT SortOrder FROM cs_Posts where PostID = @PostID)),
	AttachmentFilename,ContentType, IsRemote, FriendlyFileName, ContentSize, [FileName],p.Created, p.Height, p.Width,
	IsModerator = 0, -- (SELECT Count(*) FROM cs_Moderators WHERE UserID = U.cs_UserID),
	Replies = T.TotalReplies, -- (SELECT COUNT(*) FROM cs_Posts P2 (nolock) WHERE P2.ParentID = P.PostID AND P2.PostLevel != 1),
	PrevThreadID = 0,
	NextThreadID = 0,
	UserIsTrackingThread = 0,
	IsTracked = Convert(bit,0) -- Convert(bit, (Select Count(*) FROM cs_TrackedThreads where UserID = @UserID and ThreadID = P.ThreadID))
	, P.PostStatus, P.SpamScore
FROM 
	cs_vw_PostsWithAttachmentDetails P,
	cs_Threads T,
	cs_vw_Users_FullUser U
WHERE 
	P.PostID = @PostID AND P.SettingsID = @SettingsID and T.SettingsID = @SettingsID AND
	U.SettingsID = @SettingsID AND
	P.ThreadID = T.ThreadID AND
	P.UserID = U.cs_UserID AND
	P.IsApproved <> case @IsApprovedFilter when 1 then 0 else -1 END

	IF @IncludeCategories = 1
	Begin
		Select [Name]
		FROM   cs_Post_Categories PC, cs_Posts_InCategories PIC
		Where  PC.CategoryID = PIC.CategoryID AND PIC.PostID = @PostID
	End
End



GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT  EXECUTE  ON [dbo].[cs_weblog_Post_Get]  TO [public]
GO


/***********************************************
* Sproc: cs_weblog_Post_Update
* File Date: 11/29/2006 10:07:31 AM
***********************************************/
Print 'Creating...cs_weblog_Post_Update'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_weblog_Post_Update]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_weblog_Post_Update]
GO






CREATE  PROCEDURE [dbo].cs_weblog_Post_Update
(
	@PostID	int,
	@SectionID int,
	@Subject	nvarchar(256),
	@Body		ntext,
	@FormattedBody	ntext,
	@EmoticonID	int = 0,
	@IsSticky 	bit = null,
	@StickyDate 	datetime = null,
	@IsLocked	bit,
	@IsApproved     bit = 0,
	@IsTracked      bit = 0,
	@EditedBy	int,
	@PostMedia int = 0, 
	@Excerpt nvarchar(500) = null,
	@PostName nvarchar(256) = null,
	@TitleUrl nvarchar(256) = null,
	@PostConfig int = 0,
	@BlogPostType tinyint = 1,
	@Categories nvarchar(4000) = null,
	@PropertyNames ntext = null,
	@PropertyValues ntext = null,
	@SettingsID int,
	@UserTime datetime,
	@PostDate datetime,
	@PostStatus int = 0,
	@SpamScore int = 0
)
AS

if(@PostName is not null)
Begin

	if exists(Select p.PostID FROM cs_Posts p where p.SectionID = @SectionID and p.PostName = @PostName and p.ApplicationPostType = @BlogPostType and p.PostID <> @PostID)
	Begin
		Return 2
	End
End

	DECLARE @ThreadID int
	Declare @ParentID int
	--DECLARE @PostDate datetime

	Select @ThreadID = ThreadID, @ParentID = ParentID FROM cs_Posts where PostID = @PostID

	-- this sproc updates a post (called from the moderate/admin page)
	UPDATE 
		cs_Posts 
	SET
		Subject = @Subject,
		Body = @Body,
		FormattedBody = @FormattedBody,
		IsLocked = @IsLocked,
		EmoticonID = @EmoticonID,
		IsApproved = @IsApproved,
		PropertyNames = @PropertyNames,
		PropertyValues = @PropertyValues,
		PostDate = @PostDate,
		PostName = @PostName,
		UserTime = @UserTime,
		PostConfiguration = @PostConfig,
		ApplicationPostType = @BlogPostType,
		PostMedia = @PostMedia,
		PostStatus = @PostStatus,
		SpamScore = @SpamScore
		
	WHERE 
		PostID = @PostID and SettingsID = @SettingsID


	if(@PostID = @ParentID)
	Begin
		Update cs_Threads Set IsApproved = @IsApproved Where ThreadID = @ThreadID
	End
	


	-- Allow thread to update sticky properties.
	IF (@IsSticky IS NOT NULL) AND (@StickyDate IS NOT NULL)
	BEGIN
		-- Get the thread and postdate this applies to
		SELECT 
			@ThreadID = ThreadID,
			@PostDate = PostDate 
		FROM 
			cs_Posts 
		WHERE 
			PostID = @PostID and SettingsID = @SettingsID

		IF (@StickyDate > '1/1/2000')
		BEGIN
			-- valid date range given
			UPDATE
				cs_Threads
			SET
				IsSticky = @IsSticky,
				StickyDate = @StickyDate
			WHERE 
				ThreadID = @ThreadID  and SettingsID = @SettingsID
		END
		ELSE BEGIN
			-- trying to remove a sticky
			UPDATE
				cs_Threads
			SET
				IsSticky = @IsSticky,
				StickyDate = @PostDate
			WHERE 
				ThreadID = @ThreadID  and SettingsID = @SettingsID		
		END
	END

	IF(@BlogPostType = 1 OR @BlogPostType = 2)
	BEGIN


		IF @IsTracked = 1
		BEGIN
			-- If a row already exists to track this thread for this user, do nothing - otherwise add the row
			IF NOT EXISTS ( SELECT ThreadID FROM cs_TrackedThreads (nolock) WHERE ThreadID = @ThreadID AND UserID = @EditedBy )
				INSERT INTO cs_TrackedThreads ( ThreadID, UserID, SettingsID )
			VALUES	( @ThreadID, @EditedBy, @SettingsID)
		END
		Else
		Begin
			DELETE FROM cs_TrackedThreads where ThreadID = @ThreadID and UserID = @EditedBy and SettingsID = @SettingsID
		End


	exec cs_Posts_UpdatePostsInCategories @Categories, @SectionID, @PostID, @SettingsID, 1
	END


		UPDATE
			cs_Threads 	
		SET 
			TotalReplies = (SELECT COUNT(*) FROM cs_Posts p WHERE P.ApplicationPostType & 12 <> 0 and   p.ThreadID = @ThreadID AND p.IsApproved = 1 AND p.PostLevel > 1)
		WHERE
			ThreadID = @ThreadID

	--exec cs_weblog_UpdateContentHistory @SectionID, @BlogPostType

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_weblog_Post_Update] to public
go

/***********************************************
* Sproc: cs_weblog_Search
* File Date: 11/29/2006 10:07:31 AM
***********************************************/
Print 'Creating...cs_weblog_Search'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_weblog_Search]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_weblog_Search]
GO

/***********************************************
* Sproc: cs_weblog_Search_PostReindex
* File Date: 11/29/2006 10:07:30 AM
***********************************************/
Print 'Creating...cs_weblog_Search_PostReindex'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_weblog_Search_PostReindex]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_weblog_Search_PostReindex]
GO




/***********************************************
* Sproc: cs_weblog_Threads_GetThreadSet
* File Date: 11/29/2006 10:07:31 AM
***********************************************/
Print 'Creating...cs_weblog_Threads_GetThreadSet'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_weblog_Threads_GetThreadSet]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_weblog_Threads_GetThreadSet]
GO

--Replaced by cs_shared_Threads_GetThreadSet
/***********************************************
* Sproc: cs_weblog_TrackedThreadsByUser
* File Date: 11/29/2006 10:07:31 AM
***********************************************/
Print 'Creating...cs_weblog_TrackedThreadsByUser'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_weblog_TrackedThreadsByUser]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_weblog_TrackedThreadsByUser]
GO



CREATE PROCEDURE dbo.cs_weblog_TrackedThreadsByUser
(
	@SectionID int,
	@UserID int,
	@SettingsID int
)
AS
SET Transaction Isolation Level Read UNCOMMITTED
BEGIN


--Now we need the main post
	SELECT
		P.PostID, P.ThreadID, P.ParentID, P.PostAuthor, P.UserID, P.SectionID, P.PostLevel, P.SortOrder, P.Subject, P.PostDate, P.IsApproved,
		P.IsLocked, P.IsIndexed, P.TotalViews, P.Body, P.FormattedBody, P.IPAddress, P.PostType, P.PostMedia, P.EmoticonID, P.SettingsID, P.AggViews,
		P.PropertyNames as PostPropertyNames, P.PropertyValues as PostPropertyValues,
		T.*, U.*,P.PostName, P.UserTime, P.ApplicationPostType, P.PostConfiguration,
		P.Points as PostPoints,
		T.IsLocked,
		T.IsSticky,
		Username = P.PostAuthor,
		EditNotes = '',
		AttachmentFilename = null, -- ISNULL ( (SELECT [FileName] FROM cs_PostAttachments WHERE PostID = P.PostID), ''),
		Replies = 0,-- (SELECT COUNT(P2.PostID) FROM cs_Posts P2 (nolock) WHERE P2.ParentID = P.PostID AND P2.PostLevel != 1),
		IsModerator = 0, --(SELECT count(UserID) from cs_Moderators where UserID = @UserID),
		HasRead = 0, -- not used
		P.PostStatus, P.SpamScore
FROM
		dbo.cs_TrackedThreads TT INNER JOIN
		dbo.cs_Threads T ON TT.ThreadID = T.ThreadID INNER JOIN
		dbo.cs_Posts P (nolock) ON T.ThreadID = P.ThreadID INNER JOIN
		dbo.cs_vw_Users_FullUser U ON TT.UserID = U.cs_UserID
WHERE
		(TT.SettingsID = @SettingsID) 
		AND (TT.UserID = @UserID) 
		AND (T.SectionID = @SectionID) 
		AND (P.PostLevel = 1) 
		AND (P.IsApproved = 1)


END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].cs_weblog_TrackedThreadsByUser to public
go

















GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT  EXECUTE  ON [dbo].[cs_weblog_TrackedThreadsByUser]  TO [public]
GO


/***********************************************
* Sproc: cs_weblog_UpdateContentHistory
* File Date: 11/29/2006 10:07:31 AM
***********************************************/
Print 'Creating...cs_weblog_UpdateContentHistory'

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_weblog_UpdateContentHistory]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_weblog_UpdateContentHistory]
GO



/* TO ADD existing blog data
Insert cs_weblog_Weblogs (SectionID)
Select SectionID FROM cs_Sections where applicationtype = 1
*/

CREATE Proc [dbo].cs_weblog_UpdateContentHistory
(
	@SectionID int,
	@BlogPostTypeFilter tinyint = 0
)
as
SET Transaction Isolation Level Read UNCOMMITTED
If @BlogPostTypeFilter = 1
BEGIN

	Declare @MostRecentPostID int
	Declare @MostRecentPostDate datetime
	Declare @MostRecentPostName nvarchar(256)
	Declare @MostRecentPostAuthorID int
	Declare @MostRecentPostAuthorName nvarchar(256)
	Declare @MostRecentPostSubject nvarchar(256)
	Declare @PostCount int

	--Get Post Info
	Select Top 1 
		@MostRecentPostID = P.PostID, 
		@MostRecentPostDate =  P.PostDate, 
		@MostRecentPostAuthorID = UserID, 
		@MostRecentPostAuthorName = PostAuthor, 
		@MostRecentPostName = PostName,
		@MostRecentPostSubject = Subject 
	FROM cs_Posts P
	where P.ApplicationPostType = 1 and P.SectionID = @SectionID and P.IsApproved = 1 Order by P.PostDate Desc

	Select @PostCount = (Select Count(*) FROM cs_Posts P where P.SectionID = @SectionID and P.IsApproved = 1 and ApplicationPostType = 1)

	update cs_weblog_Weblogs
	Set
		MostRecentPostID = isnull(@MostRecentPostID,0),
		MostRecentPostDate = isnull(@MostRecentPostDate,getdate()),
		MostRecentPostAuthorID = isnull(@MostRecentPostAuthorID,0),
		MostRecentPostAuthor = isnull(@MostRecentPostAuthorName,''),
		MostRecentPostName = @MostRecentPostName,
		MostRecentPostSubject = isnull(@MostRecentPostSubject,''),
		PostCount = @PostCount
	Where SectionID = @SectionID
END
Else If @BlogPostTypeFilter = 2
BEGIN

	Declare @MostRecentArticleID int
	Declare @MostRecentArticleDate datetime
	Declare @MostRecentArticleName nvarchar(256)
	Declare @MostRecentArticleAuthorID int
	Declare @MostRecentArticleAuthorName nvarchar(256)
	Declare @MostRecentArticleSubject nvarchar(256)
	Declare @ArticleCount int

--Get Article Info
	Select Top 1 
		@MostRecentArticleID = P.PostID, 
		@MostRecentArticleDate = P.PostDate, 
		@MostRecentArticleAuthorID = UserID, 
		@MostRecentArticleAuthorName = PostAuthor, 
		@MostRecentArticleName = PostName,
		@MostRecentArticleSubject = Subject
	FROM cs_Posts P
	where P.ApplicationPostType = 2 and P.SectionID = @SectionID and P.IsApproved = 1 Order by P.PostDate Desc

	Select @ArticleCount = (Select Count(*) FROM cs_Posts P where P.SectionID = @SectionID and P.IsApproved = 1 and ApplicationPostType = 2)


	update cs_weblog_Weblogs
	Set
		MostRecentArticleID = isnull(@MostRecentArticleID,0),
		MostRecentArticleDate = isnull(@MostRecentArticleDate,getdate()),
		MostRecentArticleAuthorID = isnull(@MostRecentArticleAuthorID,0),
		MostRecentArticleAuthor = isnull(@MostRecentArticleAuthorName,''),
		MostRecentArticleName = @MostRecentArticleName,
		MostRecentArticleSubject = isnull(@MostRecentArticleSubject,''),
		ArticleCount = @ArticleCount
	Where SectionID = @SectionID
End
ELSE If @BlogPostTypeFilter = 4
BEGIN
	Declare @CommentCount int
	Select @CommentCount = (Select Count(*) FROM cs_Posts P where P.SectionID = @SectionID and P.IsApproved = 1 and ApplicationPostType = 4)
	update cs_weblog_Weblogs
	Set
		CommentCount = @CommentCount
	Where SectionID = @SectionID
END
ELSE If @BlogPostTypeFilter = 8
BEGIN
	Declare @TrackBackCount int
	Select @TrackBackCount = (Select Count(*) FROM cs_Posts P where P.SectionID = @SectionID and P.IsApproved = 1 and ApplicationPostType = 8)
	update cs_weblog_Weblogs
	Set
		TrackbackCount = @TrackBackCount
	Where SectionID = @SectionID
END

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_weblog_UpdateContentHistory] to public
go
/***********************************************
* Sproc: cs_weblog_UpdateWeblogRecentContent_Job
* File Date: 11/29/2006 10:07:32 AM
***********************************************/
Print 'Creating...cs_weblog_UpdateWeblogRecentContent_Job'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_weblog_UpdateWeblogRecentContent_Job]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_weblog_UpdateWeblogRecentContent_Job]
GO



Create Proc [dbo].cs_weblog_UpdateWeblogRecentContent_Job
(
	@SettingsID int
) 

as

SET Transaction Isolation Level Read UNCOMMITTED

Set NOCount On

Update cs_weblog_weblogs
Set 
	MostRecentPostID = P.PostID, 
	MostRecentPostDate = P.UserTime, 
	MostRecentPostName = P.PostName, 
	MostRecentPostAuthorID = P.UserID, 
	MostRecentPostAuthor = P.PostAuthor, 
	MostRecentPostSubject = P.Subject
FROM
	cs_Posts p, 
	(Select Max(p.PostID) as PostID, p.SectionID FROM cs_Posts p where p.ApplicationPostType = 1 and p.UserTime <= getdate() and p.SettingsID = @SettingsID Group by p.SectionID) sub
where
	p.PostID = sub.PostID 
	and cs_weblog_weblogs.SectionID = sub.SectionID 
	and cs_weblog_weblogs.SettingsID = @SettingsID



--We may be able to can the articles part
Update cs_weblog_weblogs
Set 
	MostRecentArticleID = P.PostID , 
	MostRecentArticleDate = P.UserTime, 
	MostRecentArticleName = P.PostName, 
	MostRecentArticleAuthorID = P.UserID, 
	MostRecentArticleAuthor = P.PostAuthor, 
	MostRecentArticleSubject = P.Subject
FROM 
	cs_Posts p, 
	(Select Max(p.PostID) as PostID, p.SectionID FROM cs_Posts p where  p.ApplicationPostType = 2 and p.UserTime <= getdate() and p.SettingsID = @SettingsID Group by p.SectionID) sub
where 
	p.PostID = sub.PostID 
	and cs_weblog_weblogs.SectionID = sub.SectionID 
	and cs_weblog_weblogs.SettingsID = @SettingsID

--Update Count Items
update cs_Weblog_Weblogs
Set
	PostCount = (Select Count(*) FROM cs_Posts p where  p.ApplicationPostType = 1 and p.IsApproved = 1 and p.SectionID =cs_Weblog_Weblogs.SectionID),
	ArticleCount = (Select Count(*) FROM cs_Posts p where  p.ApplicationPostType = 2 and p.IsApproved = 1 and p.SectionID =cs_Weblog_Weblogs.SectionID),
	CommentCount = (Select Count(*) FROM cs_Posts p where  p.ApplicationPostType = 4 and p.IsApproved = 1 and p.SectionID =cs_Weblog_Weblogs.SectionID),
	TrackBackCount = (Select Count(*) FROM cs_Posts p where  p.ApplicationPostType = 8 and p.IsApproved = 1 and p.SectionID =cs_Weblog_Weblogs.SectionID)
where 
	cs_Weblog_Weblogs.SettingsID = @SettingsID


-- Update Weblog Section records. 
-- NOTE: Other applications update the Section table stats via cs_system_UpdateForum, called from cs_Post_CreateUpdate
UPDATE cs_Sections
SET
	TotalPosts = isnull((Select Count(*) FROM cs_Posts p where p.SectionID = cs_Sections.SectionID and p.IsApproved = 1), 0),
	TotalThreads = isnull((Select Count(*) FROM cs_Posts p where p.SectionID = cs_Sections.SectionID and p.IsApproved = 1 and p.PostLevel = 1), 0),
	-- For weblogs, only count feedback that is not approved (ignore posts/articles)
	PostsToModerate = isnull((SELECT Count(*) FROM cs_Posts p WHERE p.SectionID = cs_Sections.SectionID AND p.IsApproved = 0 and p.PostLevel > 1 and (P.PostStatus & 2) <> 2), 0)
WHERE
	cs_Sections.SettingsID = @SettingsID
	and cs_Sections.ApplicationType = 1



GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_weblog_UpdateWeblogRecentContent_Job] to public
go

/***********************************************
* Sproc: cs_weblog_Weblogs_Get
* File Date: 11/29/2006 10:07:32 AM
***********************************************/
Print 'Creating...cs_weblog_Weblogs_Get'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_weblog_Weblogs_Get]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_weblog_Weblogs_Get]
GO




CREATE        PROCEDURE [dbo].cs_weblog_Weblogs_Get
(
	@SettingsID	int
)
AS

SET Transaction Isolation Level Read UNCOMMITTED
-- Return all the forums

SELECT 
	F.[SectionID], F.[SettingsID], F.[IsActive], F.[ParentID], F.[GroupID], F.[Name], F.[NewsgroupName], F.[Description], F.[DateCreated], F.[Url], F.[IsModerated], F.[DaysToView], F.[SortOrder], F.[TotalPosts], F.[TotalThreads], F.[DisplayMask], F.[EnablePostStatistics], F.[EnablePostPoints], F.[EnableAutoDelete], F.[EnableAnonymousPosting], F.[AutoDeleteThreshold], F.[MostRecentThreadID], F.[MostRecentThreadReplies], F.[PostsToModerate], F.[ForumType], F.[IsSearchable], F.[ApplicationType], F.[ApplicationKey], 
	F.PropertyNames as SectionPropertyNames, F.PropertyValues as SectionPropertyValues, F.[DefaultLanguage], F.[DiskUsage], W.*,
	null as	LastUserActivity
		
FROM
	cs_Sections F, cs_weblog_Weblogs W
WHERE
	F.SettingsID = @SettingsID AND
	 ApplicationType = 1 AND F.SectionID = W.SectionID


exec cs_Section_Permissions_Get @SettingsID, 0, 1
/*
SELECT
	P.*, F.ApplicationKey
FROM
	cs_SectionPermissions P,
	cs_Sections F,
	cs_UserProfile U,
	aspnet_UsersInRoles R
	
WHERE
	P.RoleID = R.RoleId AND
	U.MembershipID = R.UserId and
	(U.UserID = @UserID )--OR U.UserID = 0) 
	and F.ApplicationType = 1 and F.SectionID = P.SectionID
*/









GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[cs_weblog_Weblogs_Get] to public
go
/***********************************************
* Sproc: files_Comments_GetComments
* File Date: 11/29/2006 10:07:30 AM
***********************************************/
Print 'Creating...files_Comments_GetComments'

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[files_comments_getComments]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[files_comments_getComments]
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

CREATE  PROCEDURE [dbo].[files_comments_getComments]
(
	@SectionID int,
	@PageIndex int, 
	@PageSize int,
	@sqlPopulate ntext,
	@UserID int,
	@IncludePageIndex bit,
	@SettingsID int,
	@TotalRecords int output
)
AS
SET Transaction Isolation Level Read UNCOMMITTED

DECLARE @PageLowerBound int
DECLARE @PageUpperBound int
DECLARE @RowsToReturn int
DECLARE @TotalThreads int

-- First set the rowcount
SET @RowsToReturn = @PageSize * (@PageIndex + 1)


-- Set the page bounds
SET @PageLowerBound = @PageSize * @PageIndex
SET @PageUpperBound = @PageLowerBound + @PageSize + 1



-- Create a temp table to store the select results
CREATE TABLE #PageIndex 
(
	IndexID int IDENTITY (1, 1) NOT NULL,
	PostID int
)

--CREATE INDEX page_index ON #PageIndex(IndexID)

INSERT INTO #PageIndex (PostID)
EXEC (@sqlPopulate)

SET @TotalRecords = @@rowcount

SET ROWCOUNT @RowsToReturn

SELECT 
	SortOrder = jPI.IndexID,
	jP.PostID, jP.ThreadID, jP.ParentID, jP.PostAuthor, jP.UserID, jP.SectionID, jP.PostLevel, jP.SortOrder, jP.Subject, jP.PostDate, jP.IsApproved,
	jP.IsLocked, jP.IsIndexed, jP.TotalViews, jP.Body, jP.FormattedBody, jP.IPAddress, jP.PostType, jP.PostMedia, jP.EmoticonID, jP.SettingsID, jP.AggViews,
	jP.PostPropertyNames, jP.PostPropertyValues,
	jP.PostConfiguration, jP.UserTime, jP.ApplicationPostType, jP.PostName, jP.PostStatus, jP.SpamScore,
	jP.Points as PostPoints, jP.RatingSum as PostRatingSum, jP.TotalRatings as PostTotalRatings,
	HasRead = 1,
	jT.*, jU.*,
	Username = jP.PostAuthor,
	ThreadStarterAuthor = jT.PostAuthor,
	ThreadStartDate = jT.PostDate,	
	EditNotes = (SELECT EditNotes FROM cs_PostEditNotes WHERE PostID = jP.PostID),
	AttachmentFilename = ISNULL ( (SELECT [FileName] FROM cs_PostAttachments WHERE PostID = jP.PostID), ''),
	Replies = 0, --not used(SELECT COUNT(P2.PostID) FROM cs_Posts P2 (nolock) WHERE P2.ParentID = P.PostID AND P2.PostLevel != 1),
	IsModerator = 0 -- not used
FROM 
	#PageIndex jPI
	JOIN cs_vw_PostsWithAttachmentDetails jP ON jPI.PostID = jP.PostID
	JOIN cs_Threads jT ON jP.ThreadID = jT.ThreadID
	JOIN cs_vw_Users_FullUser jU ON jU.cs_UserID = jP.UserID
WHERE 
	jPI.IndexID > @PageLowerBound
	AND jPI.IndexID < @PageUpperBound
	--AND jP.PostLevel = 1 	-- PostLevel=1 should mean it's a top-level thread starter,
	AND jp.SettingsID = @SettingsID AND jT.SettingsID = @SettingsID and jU.SettingsID = @SettingsID 
ORDER BY
	jPI.IndexID	-- this is the ordering system we're using populated from the @sqlPopulate

SET ROWCOUNT 0

If @IncludePageIndex = 1
BEGIN
	SELECT IndexID, PostID from #PageIndex ORDER BY IndexID
END

DROP TABLE #PageIndex
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[files_Comments_GetComments] to public
go

/***********************************************
* Sproc: files_Downloads_Log
* File Date: 11/29/2006 10:07:30 AM
***********************************************/
Print 'Creating...files_Downloads_Log'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[files_Downloads_Log]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[files_Downloads_Log]
GO

CREATE PROCEDURE [dbo].files_Downloads_Log
	@PostID int,
	@UserID int
AS

INSERT INTO files_Downloads (UserID, PostID, DownloadDate) VALUES (@UserID, @PostID, getdate())

GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].files_Downloads_Log to public
go
/***********************************************
* Sproc: files_Entries_GetEntries
* File Date: 11/29/2006 10:07:31 AM
***********************************************/
Print 'Creating...files_Entries_GetEntries'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS OFF 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[files_Entries_GetEntries]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[files_Entries_GetEntries]
GO

CREATE PROCEDURE dbo.files_Entries_GetEntries
(
	@SectionID int,
	@PageIndex int, 
	@PageSize int,
	@sqlPopulate nText,
	@UserID int,
	@IncludeCategories bit,
	@SettingsID int,
	@TotalRecords int output
)
AS


DECLARE @PageLowerBound int
DECLARE @PageUpperBound int
DECLARE @RowsToReturn int
DECLARE @TotalThreads int

-- First set the rowcount
SET @RowsToReturn = @PageSize * (@PageIndex + 1)


-- Set the page bounds
SET @PageLowerBound = @PageSize * @PageIndex
SET @PageUpperBound = @PageLowerBound + @PageSize + 1

-- Create a temp table to store the select results
CREATE TABLE #PageIndex 
(
	IndexID int IDENTITY (1, 1) NOT NULL,
	PostID int
)


INSERT INTO #PageIndex (PostID)
EXEC (@sqlPopulate)

SET ROWCOUNT @RowsToReturn

SELECT 
	jT.*,
	jP.PostID, jP.ThreadID, jP.ParentID, jP.PostAuthor, jP.UserID, jP.SectionID, jP.PostLevel, jP.SortOrder, jP.Subject, jP.PostDate, jP.IsApproved,
	jP.IsLocked, jP.IsIndexed, jP.TotalViews, jP.Body, jP.FormattedBody, jP.IPAddress, jP.PostType, jP.PostMedia, jP.EmoticonID, jP.SettingsID, jP.AggViews,
	jP.PostPropertyNames, jP.PostPropertyValues,
	jP.Points as PostPoints,
	jP.AttachmentFilename,jP.ContentType, jP.IsRemote, jP.Height, jP.Width, jP.FriendlyFileName, jP.ContentSize, jP.[FileName],jP.Created,
	HasRead = 1,
	UserName = jT.PostAuthor,
	Replies = (SELECT COUNT(P2.PostID) FROM cs_Posts P2 (nolock) WHERE P2.ParentID = jP.PostID AND P2.PostLevel != 1),
	Downloads = (SELECT COUNT(fD.UserID) FROM files_Downloads fD (nolock) WHERE fD.PostID = jP.PostID)
FROM 
	#PageIndex jPI
	JOIN cs_vw_PostsWithAttachmentDetails jP ON jPI.PostID = jP.PostID
	JOIN cs_Threads jT ON jP.ThreadID = jT.ThreadID
WHERE 
	jPI.IndexID > @PageLowerBound
	AND jPI.IndexID < @PageUpperBound
	AND jP.PostLevel = 1 	-- PostLevel=1 should mean it's a top-level thread starter,
	AND jp.SettingsID = @SettingsID and jT.SettingsID = @SettingsID
ORDER BY
	jPI.IndexID	-- this is the ordering system we're using populated from the @sqlPopulate

Select @TotalRecords = Count(*) FROM #PageIndex

IF @IncludeCategories = 1
Begin

Select 
	Cats.[Name], jP.PostID
FROM 
	#PageIndex jPI
	JOIN cs_Posts jP ON jPI.PostID = jP.PostID
	JOIN cs_Threads jT ON jT.ThreadID = jP.ThreadID
	JOIN cs_Posts_InCategories PIC on jP.PostID = PIC.PostID
	JOIN cs_Post_Categories Cats on PIC.CategoryID = Cats.CategoryID
WHERE 
	jPI.IndexID > @PageLowerBound
	AND jPI.IndexID < @PageUpperBound
	AND jP.PostLevel = 1 and jT.SettingsID = @SettingsID and jP.SettingsID = @SettingsID


End

DROP TABLE #PageIndex
GO

grant execute on [dbo].[files_Entries_GetEntries] to public
go

/***********************************************
* Sproc: files_Entry_Get
* File Date: 11/29/2006 10:07:31 AM
***********************************************/
Print 'Creating...files_Entry_Get'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[files_Entry_Get]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[files_Entry_Get]
GO







CREATE        PROCEDURE [dbo].files_Entry_Get
/*

	Procedure for getting basic information on a single post.

*/
(
	@PostID int,
	@UserID int,
	@TrackViews bit,
	@SettingsID int
) AS
DECLARE @NextThreadID int
DECLARE @PrevThreadID int
DECLARE @ThreadID int 
DECLARE @SectionID int
DECLARE @SortOrder int
DECLARE @IsApproved bit

SELECT 
	@ThreadID = ThreadID, 
	@SectionID = SectionID, 
	@SortOrder=SortOrder,
	@IsApproved = IsApproved
FROM 
	cs_Posts (nolock) 
WHERE 
	PostID = @PostID and SettingsID = @SettingsID

DECLARE @TrackingThread bit

IF @TrackViews = 1
BEGIN
	-- Update the counter for the number of times this post is viewed
	UPDATE cs_Posts SET TotalViews = (TotalViews + 1) WHERE PostID = @PostID and SettingsID = @SettingsID
	UPDATE cs_Threads SET TotalViews = (TotalViews + 1) WHERE ThreadID = @ThreadID and SettingsID = @SettingsID
END

-- If @UserID is 0 the user is anonymous
IF @UserID > 0 AND @IsApproved = 1
BEGIN

	-- Mark the post as read
	-- *********************
	IF NOT EXISTS (SELECT ThreadID FROM cs_ThreadsRead WHERE ThreadID = @ThreadID AND UserID = @UserID and SettingsID = @SettingsID)
		INSERT INTO cs_ThreadsRead (UserID, ThreadID, SectionID, SettingsID) VALUES (@UserID, @ThreadID, @SectionID, @SettingsID)

END

-- get the anonymous user id for this site
if( @UserID = 0 ) 
BEGIN
	exec cs_GetAnonymousUserID @SettingsID, @UserID output
END


IF EXISTS(SELECT ThreadID FROM cs_TrackedThreads (nolock) WHERE ThreadID = @ThreadID AND UserID=@UserID)
	SELECT @TrackingThread = 1
ELSE
	SELECT @TrackingThread = 0

SELECT
	P.PostID, P.ThreadID, P.ParentID, P.PostAuthor, P.UserID, P.SectionID, P.PostLevel, P.SortOrder, P.Subject, P.PostDate, P.IsApproved,
	P.IsLocked, P.IsIndexed, P.TotalViews, P.Body, P.FormattedBody, P.IPAddress, P.PostType, P.PostMedia, P.EmoticonID, P.SettingsID, P.AggViews,
	P.PostPropertyNames, P.PostPropertyValues,
	P.Points as PostPoints,
	P.PostAuthor as [Username],
	T.ThreadDate,
	T.StickyDate,
	T.IsLocked,
	T.IsSticky,
	T.RatingSum,
	T.TotalRatings,
	HasRead = 0,
	EditNotes = (SELECT EditNotes FROM cs_PostEditNotes WHERE PostID = P.PostID),
	IndexInThread = (SELECT Count(PostID) FROM cs_Posts P1 WHERE IsApproved = 1 AND ThreadID = @ThreadID AND SortOrder <= (SELECT SortOrder FROM cs_Posts where PostID = @PostID)),
	AttachmentFilename,ContentType, IsRemote, FriendlyFileName, ContentSize, [FileName],p.Created, P.Height, P.Width,
	IsModerator = (SELECT Count(*) FROM cs_Moderators WHERE UserID = P.UserID),
	Replies = (SELECT COUNT(*) FROM cs_Posts P2 (nolock) WHERE P2.ParentID = P.PostID AND P2.PostLevel != 1),
	Downloads = (SELECT COUNT(fD.UserID) FROM files_Downloads fD (nolock) WHERE fD.PostID = P.PostID),
	PrevThreadID = 0,
	NextThreadID = 0,
	UserIsTrackingThread = @TrackingThread
FROM 
	cs_vw_PostsWithAttachmentDetails P,
	cs_Threads T
WHERE 
	P.PostID = @PostID AND
	P.ThreadID = T.ThreadID AND
	P.SettingsID = @SettingsID



SET QUOTED_IDENTIFIER OFF 




GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].files_Entry_Get to public
go
/***********************************************
* Sproc: files_PostAttachment_Get
* File Date: 11/29/2006 10:07:33 AM
***********************************************/
Print 'Creating...files_PostAttachment_Get'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[files_PostAttachment_Get]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[files_PostAttachment_Get]
GO







create procedure [dbo].files_PostAttachment_Get
(
	@PostID int,
	@UserID int=0,
	@LogDownload bit=0
)
AS

if @LogDownload = 1
begin
	INSERT files_Downloads (UserID, PostID, DownloadDate) VALUES (@UserID, @PostID, getdate())
end

SELECT
	*
FROM
	cs_PostAttachments
WHERE
	PostID = @PostID


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].[files_PostAttachment_Get] to public
go
/***********************************************
* Sproc: files_Post_GetSortOrder
* File Date: 11/29/2006 10:07:31 AM
***********************************************/
Print 'Creating...files_Post_GetSortOrder'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[files_Post_GetSortOrder]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[files_Post_GetSortOrder]
GO

CREATE PROCEDURE [dbo].files_Post_GetSortOrder
	@PostID int,
	@sqlPopulate nvarchar(4000),
	@SettingsID int
AS

-- Create a temp table to store the select results
CREATE TABLE #PageIndex 
(
	IndexID int IDENTITY (1, 1) NOT NULL,
	ThreadID int
)

CREATE INDEX page_index ON #PageIndex(IndexID)

INSERT INTO #PageIndex (ThreadID)
EXEC (@sqlPopulate)

SELECT IndexID
	FROM #PageIndex I
	LEFT JOIN cs_Posts P ON P.ThreadID = I.ThreadID
	WHERE P.PostID = @PostID
		AND P.SettingsID = @SettingsID

GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].files_Post_GetSortOrder to public
go
/***********************************************
* Sproc: files_Search_PostReindex
* File Date: 11/29/2006 10:07:33 AM
***********************************************/
Print 'Creating...files_Search_PostReindex'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[files_Search_PostReindex]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[files_Search_PostReindex]
GO



/***********************************************
* Sproc: files_users_WhoDownloadedFile
* File Date: 11/29/2006 10:07:33 AM
***********************************************/
Print 'Creating...files_users_WhoDownloadedFile'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[files_users_WhoDownloadedFile]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[files_users_WhoDownloadedFile]
GO

CREATE PROCEDURE [dbo].files_users_WhoDownloadedFile
(
	@PageIndex int,
	@PageSize int,
	@PostID int,
	@ReturnRecordCount bit = 0,
	@SettingsID int,
	@StartDate datetime,
	@EndDate datetime
)
AS
BEGIN
DECLARE @PageLowerBound int
DECLARE @PageUpperBound int
DECLARE @RowsToReturn int
DECLARE @TotalUsers int

-- Set the page bounds
SET @PageLowerBound = @PageSize * @PageIndex
SET @PageUpperBound = @PageLowerBound + @PageSize + 1

-- First set the rowcount
SET @RowsToReturn = @PageSize * (@PageIndex + 1)
SET ROWCOUNT @RowsToReturn

-- Create a temp table to store the select results
CREATE TABLE #PageIndexForUsers 
(
	IndexID int IDENTITY (1, 1) NOT NULL,
	LatestDownloadDate datetime,
	TotalDownloads int,
	UserID int
)	

-- Do we need to return a record count?
-- *************************************
IF (@ReturnRecordCount = 1)
    SET @TotalUsers = (SELECT count(distinct U.cs_UserId) FROM cs_vw_Users_FullUser U, files_Downloads D WHERE D.UserId = U.cs_UserId and D.PostID = @PostID and U.SettingsID = @SettingsID and D.DownloadDate between @StartDate and @EndDate)

-- Special case depending on what the user wants and how they want it ordered by
-- *************************************

INSERT INTO #PageIndexForUsers (UserID, LatestDownloadDate, TotalDownloads)
SELECT U.cs_UserID, Max(D.DownloadDate), count(*)
FROM cs_vw_Users_FullUser U, files_Downloads D 
WHERE D.UserId = U.cs_UserId 
	and D.PostID = @PostID 
	and U.SettingsID = @SettingsID 
	and D.DownloadDate between @StartDate and @EndDate
GROUP BY U.cs_UserID
ORDER BY Max(D.DownloadDate)

-- Get the user details
SELECT
	*, @PostID as PostID
FROM 
	cs_vw_Users_FullUser U (nolock),
	#PageIndexForUsers
WHERE 
	U.cs_UserID = #PageIndexForUsers.UserID AND
	#PageIndexForUsers.IndexID > @PageLowerBound AND
	#PageIndexForUsers.IndexID < @PageUpperBound  and U.SettingsID = @SettingsID 
ORDER BY
	#PageIndexForUsers.IndexID
END

-- Return the record count if necessary

IF (@ReturnRecordCount = 1)
  SELECT @TotalUsers

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on [dbo].files_users_WhoDownloadedFile  to public
go
/***********************************************
* Sproc: forums_Threads_GetThreadSet
* File Date: 11/29/2006 10:07:31 AM
***********************************************/
Print 'Creating...forums_Threads_GetThreadSet'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[forums_Threads_GetThreadSet]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[forums_Threads_GetThreadSet]
GO

/***********************************************
* Sproc: HasReadPost
* File Date: 11/29/2006 10:07:31 AM
***********************************************/
Print 'Creating...HasReadPost'

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[HasReadPost]') and OBJECTPROPERTY(id, N'IsScalarFunction') = 1)
drop function [dbo].[HasReadPost]
GO

/***********************************************
* Sproc: spam_GetRecentPostCountFromIP
* File Date: 11/29/2006 10:07:29 AM
***********************************************/
Print 'Creating...spam_GetRecentPostCountFromIP'

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[spam_GetRecentPostCountFromIP]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[spam_GetRecentPostCountFromIP]
GO

CREATE PROCEDURE [dbo].[spam_GetRecentPostCountFromIP]
(
	@IPAddress	nvarchar(50),
	@Duration	int,
	@SettingsID	int
)
AS
	SELECT	COUNT(*)
	FROM	cs_Posts
	WHERE	SettingsID = @SettingsID AND
			IPAddress = @IPAddress AND
			PostDate > DATEADD(s, -@Duration, GETDATE())

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

GRANT EXECUTE ON [dbo].[spam_GetRecentPostCountFromIP] TO PUBLIC
GO
